Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

updating the value of a key in a std::map

Tags:

c++

map

stl

Assume we have a simple structure such as the following

struct T{
  int x;
  int y;
};
T t1, t2;

Also assume that I have a map<T, int> myMap and that two structures of type T are compared using their x values only. I.e. t1 < t2 iff t1.x < t2.x. I am trying to update some of the y values of the keys over myMap. This should not affect how the map is seeing the keys. Is there any way other than removing the old element and inserting a new one?

like image 555
Pirooz Avatar asked Aug 30 '11 18:08

Pirooz


2 Answers

If you are sure that y does not participate in the "logical state" of your class and is merely an implementation detail, then you could declare it mutable:

struct T
{
  int x;
  mutable int y;
  bool operator<(const T& rhs) const { return x < rhs.x; }
};

Now you ought to be able to change y:

for (auto it = m.begin(); it != m.end(); ++it)
{
  it->first.y = -2; // ouch? But it won't invalidate the map's invariants.
}
like image 60
Kerrek SB Avatar answered Oct 15 '22 08:10

Kerrek SB


No, map cannot let you modify the keys, because that could invalidate the map invariant (ordering of the elements) — you know it won't, but the map cannot know that, so it errs on the side of caution and disallows that.

Remove and reinsert is a proper way to do it. Treat keys as immutable.

like image 29
Cat Plus Plus Avatar answered Oct 15 '22 08:10

Cat Plus Plus