Reputation: 1047
Let's assume that I have two maps of the same type and the set of keys of the second map is a subset of the keys of the first map. I want to update the first map values with values from the second map (only for the keys that the second map contains).
I have written a simple loop to do this, but I was wondering if there is a better way to write it using STL algorithms.
Code sample:
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));
//simple cycle way
for (const auto& person: map2)
{
map1[person.first] = person.second;
}
//is there some another way of doing this using STL algorithms???
for (const auto& person: map1)
{
std::cout << person.first << " " << person.second << std::endl;
}
Output:
Dad 45
Granny 77
John 24
Liza 20
Upvotes: 5
Views: 1769
Reputation: 1047
Seems like there is no more clear and better way to do it than simple cycle.
Thanks to everybody.
Upvotes: 0
Reputation: 44258
This is not much shorter but could be more efficient when value is something more complex than int
:
for( const auto &p : map2 ) {
auto r = map1.emplace( p );
if( !r.second ) r.first->second = p.second;
}
PS in comments you said that map2
is a subset of map1
, then your method probably the simplest and would not be less efficient than mine.
Upvotes: 3
Reputation: 1147
If you just want to merge them and keep elements from map2:
std::swap(map1, map2);
map1.insert(map2.begin(), map2.end());
Upvotes: 1