How to move an element without deleting and reinstalling it in boost :: multi_index_container?

I use boost :: multi_index_container to provide random access and hash access to a set of elements. I would like to change the random access index of an element without changing the index of the hash function.

Here is the code snippet:

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

using namespace std ;
using namespace boost ;
using namespace boost::multi_index ;

// class representing my elements
class Element
{
    public :
      Element(const string & new_key) : key(new_key) {}
      string key ;      // the hash-based index in the multi_index_container
      // ... many stuff skipped
    private :
      // ... many stuff skipped
} ;

typedef multi_index_container<
            Element,
            indexed_by<
                random_access< >,
                hashed_unique<
                    member<Element, string, &Element::key>
                >
            >    
        > ElementContainer ;

typedef ElementContainer::nth_index<0>::type::iterator ElementRandomIter ;
typedef ElementContainer::nth_index<1>::type::iterator ElementHashedIter ;

int main(int, char*[])
{
    ElementContainer ec ;

    // insert some elements
    ec.push_back(Element("Alice")) ;       // random-access index = 0
    ec.push_back(Element("Bob")) ;         // random-access index = 1
    ec.push_back(Element("Carl")) ;        // random-access index = 2
    ec.push_back(Element("Denis")) ;       // random-access index = 3

    // Here I want to move "Denis" to position 1
    // The (bad looking) solution I found involves removing and inserting the element
    ElementRandomIter it = ec.get<0>().begin() + 3 ;
    Element e = *(it) ;                    // store a copy
    ec.get<0>().erase(it) ;                // remove the element
    it = ec.get<0>().begin() + 1 ;
    ec.get<0>().insert(it, e) ;            // insert the copy

    // Elements are now in the following order
    // random-access index 0 : Alice
    // random-access index 1 : Denis
    // random-access index 2 : Bob
    // random-access index 3 : Carl

    return 0 ;
}

I know that even if I used only random access iterators in this example to control the elements, hashing happens behind the scenes at least twice multi_index_containerin addition to copying the object, which can be expensive.

Is there a way to change the random access index of an item inside boost::multi_indexwithout requiring expensive delete and paste-save-copy utilities?

multi_index_container, , - . !

: :)

+5

All Articles