BSalunke
BSalunke

Reputation: 11727

Can we use boost::multi_index::multi_index_container as a multiindex map?

I'm using boost::multi_index::multi_index_container<> of boost library.

I want to store the values related to each element present in this container.

Can we modify this container to use a multimap as well as it will be used as multi index container?

Upvotes: 3

Views: 1525

Answers (1)

sehe
sehe

Reputation: 393064

Of course.

However, first look at Boost Bimap, as it appears to already do what you describe:

I've given an example of how to use Boost Multi Index to emulate a map here:

The relevant type machinery looks like this:

namespace emulation {
    template <typename T1,typename T2,typename Alloc>
        struct mutable_pair
        {
            typedef T1 first_type;
            typedef T2 second_type;

            mutable_pair(Alloc alloc):first(T1(alloc)),second(T2(alloc)){}
            mutable_pair(const T1& f,const T2& s):first(f),second(s){}
            mutable_pair(const std::pair<T1,T2>& p):first(p.first),second(p.second){}

            T1         first;
            mutable T2 second;
        };

    using namespace boost::multi_index;

    template <typename Key, typename T, typename Compare, typename Allocator, typename Element = mutable_pair<Key, T, Allocator> >
        using map = multi_index_container<
            Element,
            indexed_by<
                ordered_unique<member<Element,Key,&Element::first>,Compare>
            >,
            typename Allocator::template rebind<Element>::other
        >;

  template <typename Key, typename T, typename Compare, typename Allocator, typename Element = mutable_pair<Key, T, Allocator> >
    using multimap = multi_index_container<
        Element,
        indexed_by<
            ordered_non_unique<member<Element,Key,&Element::first>,Compare>
        >,
        typename Allocator::template rebind<Element>::other
    >;
}

In case you want that answer contains a full demo, although it contains some unrelated complexity in order to use shared memory allocators.

Upvotes: 3

Related Questions