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() ));

      

+3


source to share


2 answers


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 have push_back

    or push_front

    , you need to use a more general one insterter

    , which in turn requires an iterator to specify where the insert will go. Except that it std::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

    to m1

    , 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 from m1

    .

+4


source


How about std::move

?



+5


source







All Articles