Suppose I have two cards of the same type, and the key set of the second card is a subset of the keys of the first card. I want to update the first values of the map with the values from the second map (only for keys that the second map contains).
I wrote a simple loop for this, but I was wondering if there is a better way to write it using STL algorithms.
Code example:
using PersonAgeMap = std::map<std::string, int>;
PersonAgeMap map1;
map1.insert(std::make_pair("John", 23));
map1.insert(std::make_pair("Liza", 19));
map1.insert(std::make_pair("Dad", 45));
map1.insert(std::make_pair("Granny", 77));
PersonAgeMap map2;
map2.insert(std::make_pair("John", 24));
map2.insert(std::make_pair("Liza", 20));
for (const auto& person: map2)
{
map1[person.first] = person.second;
}
for (const auto& person: map1)
{
std::cout << person.first << " " << person.second << std::endl;
}
Output:
Dad 45
Granny 77
John 24
Liza 20
source
share