【发布时间】:2016-04-17 15:00:23
【问题描述】:
假设我有两个相同类型的映射,第二个映射的键集是第一个映射的键的子集。我想用第二个映射中的值更新第一个映射值(仅适用于第二个映射包含的键)。
我已经编写了一个简单的循环来执行此操作,但我想知道是否有更好的方法来使用 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;
}
输出:
Dad 45
Granny 77
John 24
Liza 20
【问题讨论】:
-
“我已经为它编写了一个简单的循环,但有没有更好的方法来使用 STL 算法编写它?” 有点不清楚你在问什么。您应该知道
map1[person.first] = person.second;无条件插入值,无论之前是否指定了map1[person.first]。 -
正如我所写的那样,map2 中的键是 map1 中键的子集,换句话说,我有先决条件 map1 包含 map2 中的所有键,并且我想用 map2 中的值更新 map 中的值这些键。
-
您是否检查过
map接口的范围插入?您是否检查过现有算法是否可以使用? -
我想不出比你拥有的更简单的了。
-
@UlrichEckhardt Range insert 无法帮助我更新地图中的元素,这是我的情况。我检查了算法,但在这种情况下没有发现有用的东西。
标签: c++ algorithm dictionary stl