Update map with values ​​from another map

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

//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
+4
source share
3 answers

There seems to be no clearer and better way to do this than a simple loop.

Thanks to everyone.

0
source

If you just want to combine them and save the elements from map2:

std::swap(map1, map2);
map1.insert(map2.begin(), map2.end());
+1

, , - , int:

for( const auto &p : map2 ) {
    auto r = map1.emplace( p );
    if( !r.second ) r.first->second = p.second;
}

PS in the comments you said that it map2is a subset map1, then your method is probably the simplest and no less effective than mine.

+1
source

Source: https://habr.com/ru/post/1623990/


All Articles