Why C++ map.insert() doesn't overwrite

map.insert() only inserts if the container doesn't already contain an element with an equivalent key.

You should use operator[] instead:

 m[p2.first] = p2.second;

In the std::map::insert reference it is said that:

Inserts element(s) into the container, if the container doesn't already contain an element with an equivalent key.


It doesn't overwrite. However if you check the return value, there is a std::pair<iterator, bool>. If bool is true, then it was inserted. If the bool is false, then it was not inserted because of a collision. At that point, you can then overwrite the data yourself by writing to the iterator.

Tags:

C++