Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert or update a map

Tags:

c++

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?

like image 695
Chin Avatar asked Jan 30 '14 17:01

Chin


2 Answers

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

like image 130
Matthieu M. Avatar answered Nov 07 '22 05:11

Matthieu M.


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.

like image 45
eyelash Avatar answered Nov 07 '22 05:11

eyelash