所以我知道 map1.insert(map2.begin(), map2.end());
会将 map2
的所有元素插入到 map1
.
但是 map2
中的某些元素可能已经存在于 map1
中。这些元素不会更新。
e.g. map1 has { 3 : 4, 6 : 7 }
map2 has { 11: 5, 6 : 0 }
Now if I do map1.insert(map2.begin(), map2.end()), I will get
map1 = { 3: 4, 6 : 7, 11 : 5 }
But what I want is
map1 = { 3: 4, 6 : 0, 11 : 5 }
我想知道是否有像 map1.insert(map2.begin(), map2.end());
这样的函数强制更新已经存在的键?
更新:
我知道可以使用:map1[k] = v
for all key, value pairs in map2.
但是有没有像 map1.insert(map2.begin(), map2.end())
这样的函数可以做到这一点?
最佳答案
在 C++17 中,合并然后交换。
map2.merge(map1);
map2.swap(map1);
与基于插入的变体相比,这样做的好处是它只是拼接节点;没有分配,没有赋值,没有构造。
关于c++ - 将一张 map 的内容附加和替换到另一张 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44730151/