In the code below:
#include
Putting together the other answers, if you want to avoid the assumption of being default constructable you get insert-with-overwrite code that looks like this:
auto itAndWasInserted = m.insert(p1);
if (!itAndWasInserted.second) {
*(itAndWasInserted.first) = p1;
}
If you want to avoid copy construction, but also want to avoid a second seek (for re-insertion), you end up with this monster:
auto itAndWasInserted = m.insert(p1);
auto it = itAndWasInserted.first;
if (!itAndWasInserted.second) {
auto afterIt = m.erase(it);
auto newItAndWasInserted = m.insert(afterIt, p1); // Hint form of insert
it = newItAndWasInserted.first;
}
At the end of the code block, it
is an iterator pointing at the just-inserted element.
Realistically, in most cases you probably just want to use yizzlez's suggestion of operator[]
, but I thought it would be good to note the theoretically best answer.
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;
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.
This is supposed to happen. map.insert()
will only insert elements into the container if it doesn't already contain any elements, so this will ignore the later value elements assigned to it.
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.