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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With