I'm using a boost::multi_index_container to provide a random access and a hash-based access to a collection of elements. I wanted to change the random access index of an element, without changing the hash-based index.
Here is a piece of code :
# 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 only used random-access iterators in this example to manipulate elements, hashing occurs behind the scenes at least twice in the multi_index_container
, in addition to an object copy, which can be expensive.
Is there a method to change the random access index of an element inside a boost::multi_index
without requiring an expensive remove-and-insert-while-keeping-a-copy ugliness ?
I've searched in the multi_index_container
documentation, perhaps I missed something. Thanks for any advice !
Note : Sorry for possible English mistakes :)
Use relocate
:
http://www.boost.org/libs/multi_index/doc/reference/rnd_indices.html#rearrange_operations
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With