Chin
Chin

Reputation: 20675

Insert or update a map

I have a std::map. Given a <key, value> pair, I need to:

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?

Upvotes: 12

Views: 27742

Answers (2)

Matthieu M.
Matthieu M.

Reputation: 299760

There are various strategies.

If you have the chance to use C++17 (or higher), you can use insert_or_assign:

map.insert_or_assign(key, value);

Otherwise the simplest method 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).

Upvotes: 23

eyelash
eyelash

Reputation: 3700

For C++17 you can use the following code:

auto [iterator, inserted] = map.try_emplace(key, value);
if (!inserted) { iterator->second = value; }

Or even easier:

map.insert_or_assign(key, value);

It will work even for key and value types that are not default constructible or not copyable.

Upvotes: 9

Related Questions