0

I'm trying for the first time to work with boost's multi-index and I can't seem to be able to wrap my head around all the code I see on the web.

First of all: My aim is to have a container with an enum as the key for direct access as well as to be able to iterate over it based on the original order of insertion.

I have defined my boost elements like so:

struct VarMapEle {
    SolutionVariableNames first;
    uint    second;
};

struct var_tag {};
struct rand_tag {};

typedef multi_index_container<
    VarMapEle,
    indexed_by< 
        random_access<tag<rand_tag>>, // this index represents insertion order
        hashed_unique<tag<var_tag>, member<VarMapEle, SolutionVariableNames,     &VarMapEle::first>>
        >
> VariableMap;

How can I do either of the tasks I mentioned before?

Joaquín M López Muñoz
  • 5,243
  • 1
  • 15
  • 20
ginge
  • 1,962
  • 16
  • 23

1 Answers1

2

A multi_index_container can be thought of as a bunch of containers (in your example, one std::vector-like --random_acces-- and the other similar to a std::unordered_set --hashed_unique--) which happen to act on the same underlying collection of elements. Each "container" or index is accessed with get<tag>() or get<n>()where n is the 0-based order of the index as specified in the indexed_by section. So, to iterate over the elements in their order of insertion you need to access index #0 and use it as you'd do with a std::vector:

for(const VarMapEle& e:m.get<rand_tag>()){
    std::cout<<e.first<<","<<e.second<<"\n";
}

Similarly, lookup facilities are provided by index #1:

auto it=m.get<var_tag>().find(SolutionVariableNames{1});
std::cout<<it->second<<"\n";
Joaquín M López Muñoz
  • 5,243
  • 1
  • 15
  • 20
  • Thanks for the quick reply! And will the following code insert into the container? `VariableMap variableMap; variableMap.insert_(VarMapEle{ SolutionVariableNames{1}, 0});` – ginge Dec 20 '15 at 07:27
  • `variableMap`, without explicit index access via `get`, provides the interface of index #0: in your case, the `random_access` one, which does not have any `insert` (I'm asumming the trailing `_` in `insert_` is a typo) member function with such signature (inserting into a vector requires that you specify the point of insertion). – Joaquín M López Muñoz Dec 20 '15 at 10:32
  • I actually took it from some example (saw code both with insert() and insert_()). Right now I'm using .push_back() which seems to work – ginge Dec 20 '15 at 12:05