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?
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
).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With