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
You probably want:
listOf2.insert(std::make_move_iterator(listOf1.begin()),
std::make_move_iterator(listOf1.end()));
listOf1.clear();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With