c++ - 将一张 map 的内容附加和替换到另一张 map ?

标签 c++ stl unordered-map unordered

所以我知道 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/

相关文章:

c++ - 检查哪个子类是父类对象

c++ - 是否可以将 MS 单元测试从 EXE 转发到 DLL?

c++ - STL c++优先级队列可以与STL集一起使用吗?

c++ - 清空后减少 std::unordered_map 内存占用

使用自定义类类型作为键的 C++ unordered_map

c++ - 模板类型错误的通用引用

c++ - 表达式无法识别函数c++中的指针

c++ - 如何用满足某些条件的另一个 vector 中的数据填充 std::vector

c++ - 无法将 std::array 转换为 int?

C++ 关于 boost::unordered_map & boost::hash 的一些问题