使用另一个地图中的值更新地图

Pus*_*try 5 c++ algorithm dictionary stl

假设我有两个相同类型的映射,并且第二个映射的键集是第一个映射的键的子集。我想用第二个映射中的值更新第一个映射值(仅适用于第二个映射包含的键)。

我已经编写了一个简单的循环来执行此操作,但我想知道是否有更好的方法使用 STL 算法来编写它。

代码示例:

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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

  Dad 45
  Granny 77
  John 24
  Liza 20
Run Code Online (Sandbox Code Playgroud)

Pus*_*try 0

似乎没有比简单循环更清晰、更好的方法了。

谢谢大家。