Suppose I have the following:
std::map<KEY,VALUE> m1;
std::map<KEY,VALUE> m2;
What is the most direct way to move all key/value pairs from m1 into m2?
I would expect:
- m1 to be empty after this operation
- m2 may initially have pairs
- those pairs in m2 that don’t have the same key as m1 should be left alone
- those pairs in m2 that have the same key as m1 should be overwritten with m1’s pairs
Do I need a combination of calls from <algorithm>?
Solution
James Kranze’s solution satisfies my requirements.
for( const auto& p : m1 )
m2[ p.first ] = p.second;
m1.clear();
Joachim Pileborg’s recommendation will only work if m2 and m1 do not have the same key (ie m2’s value will not be overwritten by m1’s value for the same key)
std::move( m1.begin(), m1.end(), std::inserter( m2, m2.begin() ));
The most obvious solution is just to write a loop yourself:
Otherwise, I think something like the following should work:
This isn’t exactly intuitive, and I’d hesitate to use it without
comments, since:
Since
std::mapdoesn’t havepush_backorpush_front, you needto use the more general
insterter, which in turn requires an iteratorspecifying where the insertion is to take place. Except that
std::maptreats this iterator as a “hint”, and since it generally won’t be a
good hint, it will be ignored.
You actually have to copy from
m2intom1, since insertion into amap will not overwrite any existing value, and when the key is present
in both maps, you want to keep the value from
m1.