std::move

From Cppreference

Jump to: navigation, search
Defined in header <algorithm>

template< class InputIterator, class OutputIterator >
OutputIterator move( InputIterator first, InputIterator last, OutputIterator d_first );

Moves the elements in the range [first, last), to another range beginning at d_first.

Contents

[edit] Parameters

first, last - the range of elements to move
d_first - the beginning of the destination range. If d_first is within [first, last), std::move_backward must be used instead of std::move.

[edit] Return value

Output iterator to the element past the last element moved (d_first + (last - first))

[edit] Complexity

Exactly last - first move assignments.

[edit] Equivalent function

[edit] Example

The following code moves threads handles (which themselves are not copyable) from one container to another.

#include <iostream>
#include <vector>
#include <list>
#include <iterator>
#include <thread>
#include <chrono>
 
void f(int n)
{
    std::this_thread::sleep_for(std::chrono::seconds(n));
    std::cout << "thread " << n << " ended" << '\n';
}
 
int main()
{
    std::vector<std::thread> v;
    v.emplace_back(f, 1);
    v.emplace_back(f, 2);
    v.emplace_back(f, 3);
    std::list<std::thread> l;
 
    // copy() would not compile
    std::move(v.begin(), v.end(), std::back_inserter(l)); 
 
    for(auto& t : l) t.join();
}

Output:

thread 1 ended
thread 2 ended
thread 3 ended

[edit] See also

move_backward (C++11)
moves a range of elements to a new location in backwards order
(function template)