Reputation: 5007
When using a custom operator for std::map<KeyType,ValueType,Comparator>
, which by design only compares some of my KeyType's fields, it is possible that two objects KeyType k1, k2
contain different data but for the map they look like the same key. After all, this is the reason why we wrote our custom Comparator in the first place.
So if I write
map[k1] = 1;
map[k2] = 2;
with k1 and k2 such that the comparator reports them as being equal, the map will contain the key/value pair {k1, 2}
.
What is the most elegant way to replace the pair {k1, 1}
by {k2, 2}
or is the only way to erase k1 first and then insert k2?
Upvotes: 1
Views: 137
Reputation: 40070
I can find two distinct ways of replacing a key from a map with an equivalent key:
Just swap
a key with another, it is UB, but it should be fine with most of std::map
implementations:
std::swap(const_cast<Key&>(map.find(k2)->first), k2);
Demo.
Provide an adjustment const
method Key
which change it's internal state:
void adjust(const Key& other) const { value = other.value; }
An improvement being to check that this method transforms a Key
to an equivalent Key
.
Demo (improvements let to OP).
Upvotes: 1