Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How move map to other map

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

like image 345
21koizyd Avatar asked Dec 05 '22 14:12

21koizyd


2 Answers

You probably want:

listOf2.insert(std::make_move_iterator(listOf1.begin()),
               std::make_move_iterator(listOf1.end()));
listOf1.clear();
like image 173
Jarod42 Avatar answered Dec 27 '22 18:12

Jarod42


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

like image 29
Praetorian Avatar answered Dec 27 '22 19:12

Praetorian