简体   繁体   中英

C++11 STL merge using move assignment between 2 maps

Is it possible to merge map from 1 instance A to another without unnessery calls of copy constructor of B?

class A
{
    ...
    A & operator=(A && rhs);

    map<string, B> map;
};

class B
{
    B();
    B & B(B && rhs);
    ... 
}

...

A instanceOfA1;
A instanceOfA2;

B instanceOfB1;
B instanceOfB2;
B instanceOfB3;
B instanceOfB4;

instanceOfA1.map.insert( pair<string, B>("one", instanceOfB1));
instanceOfA1.map.insert( pair<string, B>("two", instanceOfB2));
instanceOfA1.map.insert( pair<string, B>("three", instanceOfB3));

instanceOfA2.map.insert( pair<string, B>("four", instanceOfB4));

instanceOfA2 = instanceOfA1;

So that map in instanceOfA2 contains all four instances of B.

EDIT: Fixed instances in code.

Is it possible to merge map from 1 instance A to another without unnessery calls of copy constructor of B?

Unfortunately, no. There was a proposal to allow elements to be removed from one map and inserted into another, but it was not accepted. There are some plans to revise the paper and make a new proposal in future.

The best you can do is to insert new elements, but make sure they use the move constructor of B instead of copying:

for (auto& p : A1)
  A2.insert(std::move(p));

This can be done with move_iterator s too:

A2.insert(std::make_move_iterator(A1.begin()), std::make_move_iterator(A1.end()));

Note that the key_type in a std::map is const , so the key type can not be moved, only the mapped types (the B objects) will be moved. That means A1 will still contain the same number of elements it had originally, but the B objects will be moved-from, and so you probably want to do this afterwards:

A1.clear();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM