我想合併兩個std::unordered_map:mapA和mapB,同時如果兩個 map 都包含相同的鍵,則保留mapA中專案的優先順序。https://www.796t.com/post/NHFoYjI=.html
例:
mapA = {{"sugar",0.1},{"salt",0.2}}
mapB = {{"sugar",0.3},{"pepper",0.4}}
结果:
result = {{"sugar",0.1},{"salt",0.2},{"pepper",0.4}}
{"sugar",0.3}忽略mapB
解决办法
auto result = mapA;
result.insert(mapB.begin(), mapB.end());
#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
unordered_map<string,double> mapA = {{"sugar",0.1},{"salt",0.2}};
unordered_map<string,double> mapB = {{"sugar",0.3},{"pepper",0.4}};
mapA.insert(mapB.begin(), mapB.end());
for (auto &i : mapA) {
cout << i.first << " " << i.second << endl;
}
return 0;
}