std::ranges::move, std::ranges::move_result
來自 cppreference.com
定義於標頭檔案 <algorithm> |
||
呼叫簽名 (Call signature) |
||
template< std::input_iterator I, std::sentinel_for<I> S, std::weakly_incrementable O > requires std::indirectly_movable<I, O> |
(1) | (C++20 起) |
template< ranges::input_range R, std::weakly_incrementable O > requires std::indirectly_movable<ranges::iterator_t<R>, O> |
(2) | (C++20 起) |
輔助型別 |
||
template< class I, class O > using move_result = ranges::in_out_result<I, O>; |
(3) | (C++20 起) |
1) 將由
[
first,
last)
定義的範圍中的元素移動到從 result 開始的另一個範圍。如果 result 位於範圍 [
first,
last)
內,則行為未定義。在這種情況下,可以使用 ranges::move_backward 代替。被移動的範圍中的元素仍將包含適當型別的有效值,但不一定與移動之前的值相同。
本頁描述的類函式實體是 演算法函式物件(非正式地稱為 niebloids),即
目錄 |
[編輯] 引數
first, last | - | 定義要移動的元素範圍的迭代器-哨兵對 |
r | - | 要移動的元素範圍 |
result | - | 目標範圍的開頭 |
[編輯] 返回值
{last, result + N},其中
1) N = ranges::distance(first, last)。
2) N = ranges::distance(r)。
[編輯] 複雜度
精確地 N 次移動賦值。
[編輯] 注意
當移動重疊範圍時,ranges::move 適用於向左移動(目標範圍的起始在源範圍之外),而 ranges::move_backward 適用於向右移動(目標範圍的結束在源範圍之外)。
[編輯] 可能實現
struct move_fn { template<std::input_iterator I, std::sentinel_for<I> S, std::weakly_incrementable O> requires std::indirectly_movable<I, O> constexpr ranges::move_result<I, O> operator()(I first, S last, O result) const { for (; first != last; ++first, ++result) *result = ranges::iter_move(first); return {std::move(first), std::move(result)}; } template<ranges::input_range R, std::weakly_incrementable O> requires std::indirectly_movable<ranges::iterator_t<R>, O> constexpr ranges::move_result<ranges::borrowed_iterator_t<R>, O> operator()(R&& r, O result) const { return (*this)(ranges::begin(r), ranges::end(r), std::move(result)); } }; inline constexpr move_fn move {}; |
[編輯] 示例
以下程式碼將執行緒物件(它們本身是*不可複製*的)從一個容器移動到另一個容器。
執行此程式碼
#include <algorithm> #include <chrono> #include <iostream> #include <iterator> #include <list> #include <thread> #include <vector> using namespace std::literals::chrono_literals; void f(std::chrono::milliseconds n) { std::this_thread::sleep_for(n); std::cout << "thread with n=" << n.count() << "ms ended" << std::endl; } int main() { std::vector<std::jthread> v; v.emplace_back(f, 400ms); v.emplace_back(f, 600ms); v.emplace_back(f, 800ms); std::list<std::jthread> l; // std::ranges::copy() would not compile, because std::jthread is non-copyable std::ranges::move(v, std::back_inserter(l)); }
輸出
thread with n=400ms ended thread with n=600ms ended thread with n=800ms ended
[編輯] 參閱
(C++20) |
以逆序將一個範圍的元素移動到一個新位置 (演算法函式物件) |
(C++20)(C++20) |
將一個範圍的元素複製到一個新位置 (演算法函式物件) |
(C++20) |
以逆序複製一個範圍的元素 (演算法函式物件) |
(C++11) |
將一個範圍的元素移動到一個新位置 (函式模板) |
(C++11) |
將引數轉換為亡值 (函式模板) |