Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging two unordered_maps with overlapping keys

Tags:

c++

c++11

I would like to merge two std::unordered_map: mapA and mapB, while keeping priority for items from mapA if both maps contain the same key.

Is there an elegant way of doing this (rather then validating each key.. my maps contain a large number of elements)?

Example:

mapA = {{"sugar",0.1},{"salt",0.2}}
mapB = {{"sugar",0.3},{"pepper",0.4}}

The result I would like to have is:

result = {{"sugar",0.1},{"salt",0.2},{"pepper",0.4}}

Ignoring the key-value {"sugar",0.3} from mapB

Thanks.

like image 233
MZHm Avatar asked Dec 16 '15 20:12

MZHm


2 Answers

Absolutely:

auto result = mapA;
result.insert(mapB.begin(), mapB.end());

The insert member functions of unordered_map do nothing if the key already exists within the container.

Demo.

like image 131
ecatmur Avatar answered Oct 17 '22 05:10

ecatmur


I know this question is tagged C++11, but for completeness it seems worth mentioning that C++17 added the merge() function if you don't care about keeping mapB intact. merge() moves all of the elements whose keys are not in mapA from mapB to mapA. If a key are in mapA, mapA remains unchanged for that element and the element remains in mapB.

https://en.cppreference.com/w/cpp/container/unordered_map/merge

like image 44
schrödinbug Avatar answered Oct 17 '22 05:10

schrödinbug