bro*_*ams 0 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 }
Run Code Online (Sandbox Code Playgroud)
我想知道是否有任何函数map1.insert(map2.begin(), map2.end());可以强制更新已经存在的密钥?
更新:我知道可以使用以下方法完成:map1[k] = v对于map2中的所有键、值对。
但是有没有类似的函数map1.insert(map2.begin(), map2.end())可以做到这一点呢?
在 C++17 中,先合并然后交换。
map2.merge(map1);
map2.swap(map1);
Run Code Online (Sandbox Code Playgroud)
与基于插入的变体相比,这样做的好处是它只拼接节点;没有分配,没有分配,没有构建。