Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to move all pairs from one std::map to another

Tags:

c++

c++11

stl

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() ));
like image 394
kfmfe04 Avatar asked Dec 28 '22 04:12

kfmfe04


2 Answers

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.

like image 193
James Kanze Avatar answered Jan 08 '23 22:01

James Kanze


How about std::move?

like image 23
Some programmer dude Avatar answered Jan 08 '23 21:01

Some programmer dude