MZHm
MZHm

Reputation: 2548

Merging two unordered_maps with overlapping keys

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.

Upvotes: 10

Views: 13101

Answers (3)

schrödinbug
schrödinbug

Reputation: 863

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

Upvotes: 4

ecatmur
ecatmur

Reputation: 157364

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.

Upvotes: 32

Anon Mail
Anon Mail

Reputation: 4770

Since std::unordered_map is unsorted, there is no other way. You will have to loop over each element in mapB and attempt to insert it in mapA. Existing elements in mapA will not be inserted.

Upvotes: -2

Related Questions