Defined in header
<algorithm> | ||
---|---|---|
template< class InputIt, class OutputIt > OutputIt move( InputIt first, InputIt last, OutputIt d_first ); | (1) | (since C++11) |
template< class ExecutionPolicy, class InputIt, class OutputIt > OutputIt move( ExecutionPolicy&& policy, InputIt first, InputIt last, OutputIt d_first ); | (2) | (since C++17) |
[first, last)
, to another range beginning at d_first
. After this operation the elements in the moved-from range will still contain valid values of the appropriate type, but not necessarily the same values as before the move.policy
. This overload does not participate in overload resolution unless std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>
is truefirst, 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. |
policy | - | the execution policy to use. See execution policy for details. |
Type requirements | ||
-
InputIt must meet the requirements of InputIterator . |
||
-
OutputIt must meet the requirements of OutputIterator . |
Output iterator to the element past the last element moved (d_first + (last - first)
).
Exactly last - first
move assignments.
The overload with a template parameter named ExecutionPolicy
reports errors as follows:
std::terminate
is called. std::bad_alloc
is thrown. template<class InputIt, class OutputIt> OutputIt move(InputIt first, InputIt last, OutputIt d_first) { while (first != last) { *d_first++ = std::move(*first++); } return d_first; } |
When moving overlapping ranges, std::move
is appropriate when moving to the left (beginning of the destination range is outside the source range) while std::move_backward
is appropriate when moving to the right (end of the destination range is outside the source range).
The following code moves thread objects (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, because std::thread is noncopyable 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
(C++11)
| moves a range of elements to a new location in backwards order (function template) |
(C++11)
| obtains an rvalue reference (function template) |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
http://en.cppreference.com/w/cpp/algorithm/move