How to add / copy an STL container object to another object if its value is not a copy, for example, standard :: thread

I want to move the std::map container object to another. In its simplest form:

 #include<map> #include<thread> #include<vector> using namespace std; int main () { map<void*, vector<thread>> m1, m2; // m1 is updated m1.insert(m2.begin(), m2.end()); // <--- problem here m2.clear(); // not required anymore } 

However, it gives an error page:

 error: use of deleted function 'std::thread::thread(const std::thread&)' 

How to do it?

+5
source share
5 answers

std::thread not constructive for copying, you will have to use an iterator that allows you to navigate:

 m1.insert(std::make_move_iterator(m2.begin()), std::make_move_iterator(m2.end()); 

std::make_move_iterator returns a specialized iterator std::move_iterator , whose access members ( operator*() and operator->() ) return rvalues ​​references, unlike built-in iterators that return lvalues. map::insert() delegates its operation map::emplace() , where it translates the argument into an element type.

Copy constructors of your threads were created because the objects returned from the built-in iterators were sent as lvalues ​​and thus were copied.

+11
source

For completeness only, in the <algorithm> there is a little-known version of std::move that follows the similar std::copy pattern.

So you can write this:

 move(begin(m2), end(m2), inserter(m1, begin(m1))); m2.clear(); 

link here

+5
source

Move them using move iterators:

 m1.insert(make_move_iterator(begin(m2)), make_move_iterator(end(m2))); 
+3
source

I do not think that you can insert a series of elements that are only moving. You should be able to std::move() individual elements:

 for (auto& element: m2) { m1.emplace(element.first, std::move(element.second)); } 
+2
source

General solution: move it.

However, although std::move() can move a single value, it cannot move a range of values. You need to write a loop:

 for (auto&& pair : m1) m2[pair.first] = std::move(pair.second) 
+1
source

Source: https://habr.com/ru/post/1209502/


All Articles