3

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?

BSalunke
  • 11,499
  • 8
  • 34
  • 68

1 Answers1

3

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.

Community
  • 1
  • 1
sehe
  • 374,641
  • 47
  • 450
  • 633
  • thank you for the descriptive and useful answer. However I'm stuck in emulation of map associative container. I tried to emulate a map which holds key and value as a "set<>" of boost:shared_ptr<>. – BSalunke Mar 31 '15 at 10:38
  • @BSalunke perhaps you should post another question showing a SSCCE of where you are stuck – sehe Mar 31 '15 at 11:02