Boost logo

Boost Users :

Subject: Re: [Boost-users] Container with insertion order
From: Igor R (boost.lists_at_[hidden])
Date: 2011-12-03 13:12:31


> Ok, now I want to make find() and erase() methods. In std::map, they return
> an iterator. Should I wrap the methods find() and erase(), to pass a const
> K& key, and return a container1:: const_iterator. is it right?

std::map::find and std::map::erase have several overloads:
http://www.cplusplus.com/reference/stl/map/find/
http://www.cplusplus.com/reference/stl/map/erase/
And none of erase() overloads returns iterator.

By the way, why don't you just inherit from multi_index_container and
add [] operator?
MIC itself already has STL-complient interace, so trying to rewrite it
is hardly worth the effort.
The following is your code, but with inheritance:

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/random_access_index.hpp>

using namespace boost::multi_index;

template<typename K,typename V>
struct mutable_pair
{
        typedef K first_type;
        typedef V second_type;
        mutable_pair():first(K()),second(V()){}
        mutable_pair(const K& f,const V&s):first(f),second(s){}
        mutable_pair(const std::pair<K,V>& p):first(p.first),second(p.second){}
        K first;
        mutable V second;
};

template<typename K,typename V>
class Ordered_Map : public multi_index_container<
        mutable_pair<K, V>,
  indexed_by< random_access<>,
  ordered_unique<member<mutable_pair<K,V>, K, &mutable_pair<K, V>::first> > >
>
{
public:
        V& operator[]( const K& key )
        {
                insert(end(), mutable_pair<K, V>(key,V()));
                return get<1>().find(key)->second;
        }
};

int main()
{
        Ordered_Map<std::string,int> myMap;
        myMap["Joe"] = 3;
        myMap["Lillo"] = 9;
        myMap["Mary"] = -3;
        for (auto i = myMap.cbegin(); i != myMap.cend(); ++i)
        std::cout << i->first << " - " << i->second << std::endl;
        std::cin.get();
        return 0;
}


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net