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?
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";