How to move a card to another card

std::map<long long, std::unique_ptr<A>> listOf1;
std::map<long long, std::unique_ptr<A>> listOf2;

      

How can I add listOf1 to listOf2? This is probably tricky, because the value of unique_ptr. Normal solution:

listOf2.insert(listOf1.begin(), listOf1.end());

      

doesn't work and gives error

Severity Code Description Project File Line Source Suppression Status Error C2280 'std :: pair :: pair (const std :: pair &)': Attempt to reference a remote function c: \ program files (x86) \ microsoft visual studio 14.0 \ vc \ include \ xmemory0 737 Build

+3


source to share


2 answers


You probably want:



listOf2.insert(std::make_move_iterator(listOf1.begin()),
               std::make_move_iterator(listOf1.end()));
listOf1.clear();

      

+11


source


If you have a standard library implementation that implements the C ++ 17 node interface , you can use map::merge

to concatenate nodes from one map

to another.

The advantage of this map::insert

is that instead of moving the building elements, the maps transfer ownership of the nodes by simply copying some of the internal pointers.



#include <map>
#include <iostream>
#include <memory>

struct A
{};

int main()
{
    std::map<long long, std::unique_ptr<A>> listOf1;
    std::map<long long, std::unique_ptr<A>> listOf2;

    listOf1[10] = std::make_unique<A>();
    listOf1[20] = std::make_unique<A>();
    listOf1[30] = std::make_unique<A>();
    listOf2[30] = std::make_unique<A>();
    listOf2[40] = std::make_unique<A>();

    listOf1.merge(listOf2);
    for(auto const& m : listOf1) std::cout << m.first << '\n';
}

      

Live demo

+2


source







All Articles