4
votes
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? Probably it's tricky because value is unique_ptr. Normall solution:

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

doesn't work and give error

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

2
What do you mean by "move"? Do you want move-assignment? Do you want to add all entries from one map to the other (and remove them from the first map)?user2357112 supports Monica
Something like: listOf2.insert(std::make_move_iterator(listOf1.begin()), std::make_move_iterator(listOf1.end())); ?Jarod42
I want add all elements from first map to second map and remove first map.21koizyd
@Jarod42 thanks, it's answer for my problem :)21koizyd
@KerrekSB what are you mind?21koizyd

2 Answers

12
votes

You probably want:

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

If you have a standard library implementation that implements the C++17 node handle interface, you can use the map::merge function to splice nodes from one map to another.

The benefit of doing this over map::insert is that instead of move constructing elements, the maps will transfer ownership of nodes by simply copying over some 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