Combining two unordered_maps with overlapping keys

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

Is there an elegant way to do this (and not check every key .. my cards contain a large number of elements)?

Example:

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

As a result, I would like to:

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

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

Thanks.

+5
source share
2 answers

Absolutely:

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

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

Demo version

+17
source

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

0
source

Source: https://habr.com/ru/post/1238426/


All Articles