开发者

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

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?


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.
}


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.


If y doesn't participate in the comparison, you can mark it as mutable, so it can be modified even when the value is constant.


The keys of std::map are const. So you cannot change it.

Also, if you use only x to compare the keys, then why do you std::map<T,int>? Why not this:

std::map<int, std::pair<T,int> > data; //where keys would be t.x

After all, in your map, keys are effectively t.x.


You can modify T::y if it does not affect comparison operator behaviour. On the other hand it is bad style to modify map's key, it should be immutable. Some implementations of Standard Library do allow to modify key.


keys are const in a map, try copying new values into a new map.


Like Cat said you shouldn't change keys for a lot of good reasons but you seem to know enough to move ahead.

Cast away the key's constness with const_cast and you can't do all kinds of damage.... err changes. Just double check that the comparison operator still returns the same after modifying it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜