Gabriel
Gabriel

Reputation: 9432

boost multi_index_container changing keys -> incorret state of container

Supposed we have a multi index container:

#include <iostream>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/random_access_index.hpp>
#include <boost/multi_index/tag.hpp>
#include <boost/multi_index/key_extractors.hpp>

struct A{
A(int i){id=i;}
    int id;
};

typedef boost::multi_index::multi_index_container<
    A * ,
    boost::multi_index::indexed_by<
        boost::multi_index::random_access<
            boost::multi_index::tag<by_insertion>
        >, // this index represents insertion order
        boost::multi_index::hashed_unique<
            boost::multi_index::tag<by_id>,
            boost::multi_index::member<A, int, &A::id>
        >
    >
> MapType;

MapType map;

map.get<1>().insert(new A(1));
map.get<1>().insert(new A(2));

(*map.get<1>().find(1))->id=4; // HERE IF I CHANGE THE KEY, I CAN NOT FIND either key=4 or 1

MapType::nth_index<1>::type::iterator it = map.get<1>().find(4);
if(it != map.get<1>().end() ){
    std::cout << "FOUND A:" << *it << std::endl;
} // DOES NOT WORK?? WHY CANT I FIND the ELement with Key 4?

The problem is now that i probably set up the boost::multi_index::member<A, int, &A::a> wrongly because when I change some key. I cannot find the element with key = 4?

Whats wrongly used here? Any help really appreciated!

Upvotes: 1

Views: 927

Answers (2)

Answering Gabriel's last comment: using a container of pointers just to have write access to the elements is overkill. You can do instead one of the following:

  • Use modify(), which checks if the modified element has to be relocated as a consequence of some key having been touched.
  • If you know you won't change a key, cast with const_cast<A&>() and modify as you please.

In general, Boost.MultiIndex has no way to grant write access only to non-key parts of the element.

Upvotes: 1

No, hashed indices do not store hash values, they always calculate it on the fly. Why do you want to change keys yet keep looking up by the old values?

Upvotes: 1

Related Questions