[英]Is there a way to copy non-conflicting map values using std::copy?
I'm looking for a way to copy values from one map into another, similar to this question , but I don't want conflicting values to be overwritten by the second map, I want the original values to remain untouched. 我正在寻找一种将值从一个映射复制到另一个映射的方法,类似于这个问题 ,但是我不希望有冲突的值被第二个映射覆盖,我希望原始值保持不变。
For example, if I had two maps {a: 1, b: 2}
, and I copied {b: 3, c: 4}
into it, the first map would be modified to {a: 1, b: 2, c: 4}
. 例如,如果我有两个地图
{a: 1, b: 2}
,并且我将{b: 3, c: 4}
复制到其中,则第一张地图将被修改为{a: 1, b: 2, c: 4}
。
Is there a way to do this using standard library functions, or do I need to do it manually through iteration and checking for conflicting values? 是否可以使用标准库函数来执行此操作,还是需要通过迭代并检查冲突值来手动执行此操作?
There's a version of map.insert
that takes two iterators. 有一个
map.insert
版本需要两个迭代器。 An insert fails if the item (key) is already present in the target map, so this does exactly what you want. 如果项目(键)已存在于目标映射中,则插入将失败,因此这正是您想要的。
#include <iostream>
#include <map>
int main() {
std::map<char, int> stuff;
stuff['a'] = 1;
stuff['b'] = 2;
std::map<char, int> stuff2;
stuff2['b'] = 3;
stuff2['c'] = 4;
stuff.insert(stuff2.begin(), stuff2.end());
for (auto i : stuff)
std::cout << i.first << "\t" << i.second << "\n";
}
Result: 结果:
a 1
b 2
c 4
You can do this using std::for_each
and a lambda: 您可以使用
std::for_each
和lambda来做到这一点:
std::map<int, int> m1 = ...;
std::map<int, int> m2 = ...;
std::for_each(m2.begin(), m2.end(),
[&m1](const std::pair<const int, int>& a)
{
if(m1.find(a.first) == m1.end())
m1.insert(a);
});
Effectively, this is just bundling up what you'd have to do manually into std::for_each
and a lambda. 实际上,这只是将您必须手动执行的操作捆绑到
std::for_each
和lambda中。 As far as I know, there's not really any nicer way of doing what you want to achieve. 据我所知,实际上并没有更好的方法来完成您想要实现的目标。
If your compiler supports emplace
(which GCC 4.7 doesn't, but 4.8 does), then you can utilize that: 如果您的编译器支持
emplace
(GCC 4.7不支持,但4.8支持),那么您可以利用它:
std::for_each(m2.begin(), m2.end(),
[&m1](const std::pair<const int, int>& a)
{
m1.emplace(a.first, a.second);
});
emplace
will preserve elements, only constructing a new element if a previous one does not exist. emplace
将保留元素,仅在前一个元素不存在时才构造一个新元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.