Insert or update a map

c++

Solution

There are various strategies.

The simplest is just to use `operator []`:

map[key] = value;

however it requires that `value` be default constructible and assignable. Furthermore, since those operations take place they might (in some case) lead to performance concerns.

Another solution:

auto const result = map.insert(std::make_pair(key, value));
if (not result.second) { result.first->second = value; }

You of course also incur the assignment cost if you update, but avoid it if the insert works.

For reference, the return value of `insert` is `std::pair<iterator, bool>` which yields an `iterator` to the element inserted or found, and a boolean indicated whether the insert was successful (`true`) or not (`false`).

Problem

I have a `std::map`. Given a `<key, value>` pair, I need to: - Modify the value in the map if the key exists, or - Insert the pair into the map if the key does not exist yet. I'm doing it like this: ``` if (map.find(key) == map.end()){ map.insert(std::pair<int, char>(key, value)); } else { map[key] = value; } ``` Is this way of doing it correct? Also, is there a faster or more idiomatic way to do this?

Original source