kfmfe04
kfmfe04

Reputation: 15327

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 into m2?

I would expect:

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

Upvotes: 4

Views: 4486

Answers (1)

James Kanze
James Kanze

Reputation: 153919

The most obvious solution is just to write a 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 isn't exactly intuitive, and I'd hesitate to use it without comments, since:

  1. Since std::map doesn't have push_back or push_front, you need to use the more general insterter, which in turn requires an iterator specifying where the insertion is to take place. Except that std::map treats this iterator as a “hint”, and since it generally won't be a good hint, it will be ignored.

  2. You actually have to copy from m2 into m1, since insertion into a map will not overwrite any existing value, and when the key is present in both maps, you want to keep the value from m1.

Upvotes: 5

Related Questions