How to move all pairs from one std :: map to another
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
to m2
?
I would expect:
- m1 will be empty after this operation
- m2 may first have pairs
- those pairs in m2 that do not have the same key as m1 should be left alone
- those pairs in m2 that have the same key as m1 must be overwritten with pairs of m1.
I need a combination of calls from <algorithm>
?
Decision
James Krantze 's solution suits my requirements.
for( const auto& p : m1 )
m2[ p.first ] = p.second;
m1.clear();
Joachim Pileborg's recommendation only works if m2 and m1 do not have the same key (i.e. m2 value will not be overwritten with m1 value for the same key)
std::move( m1.begin(), m1.end(), std::inserter( m2, m2.begin() ));
source to share
The most obvious solution is to just write the loop yourself:
for ( std::map<KEY, VALUE>::const_iterator current = m1.begin();
current != m1.end();
++ current ) {
m2[current->first] = current->second;
}
Otherwise, I think something like the following should work:
std::copy( m2.begin(), m2.end(), std::inserter( m1, m1.end() ) );
m2.clear();
m2.swap( m1 );
This is not entirely intuitive and I hesitate to use it without comment, since:
-
Since it
std::map
doesn't havepush_back
orpush_front
, you need to use a more general oneinsterter
, which in turn requires an iterator to specify where the insert will go. Except that itstd::map
treats this iterator as a "hint", and since it usually won't be a good hint, it will be ignored. -
You really need to copy from
m2
tom1
, as pasting into the map will not overwrite the existing value, and when the key is present on both maps you want to keep the value fromm1
.
source to share