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