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.
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
).