我认为标题非常清楚,这是我想要实现的示例,而无需迭代键并手动添加它们,我想知道是否存在更快的解决方案(某些功能或技术)。 ..)
示例:
std::map<int,int> a, b, c;
a[0] = 2;
a[2] = 5;
b[0] = 6;
b[1] = 1;
,结果是包含以下内容的地图c:
std::cout << c[0] << std::endl; // prints 8
std::cout << c[1] << std::endl; // prints 1
std::cout << c[2] << std::endl; // prints 5
简介:
if key exists : add the values
else create it with the current value
提前谢谢!
答案 0 :(得分:4)
这是我要实现的示例,而无需迭代键并手动添加,
我认为您不迭代地图内容就无法实现目标。
我能想到的最简单的方法是:
c = a;
for ( auto const& item : b )
{
c[item.first] += item.second;
}