std::ranges::move, std::ranges::move_result
From cppreference.com
| ヘッダー <algorithm> で定義 |
||
| 呼び出しシグネチャ |
||
| 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を使用できます。移動元の範囲内の要素は、適切な型の有効な値を保持しますが、移動前と同じ値であるとは限りません。
このページで説明されている関数のようなエンティティは、アルゴリズム関数オブジェクト(非公式にはニーブロイドとして知られている)です。つまり、
- これらのいずれかを呼び出す際に、明示的なテンプレート引数リストを指定することはできません。
- これらのいずれも実引数依存の名前探索には見えません。
- これらのいずれかが関数呼び出し演算子の左側の名前として通常の非修飾名探索によって見つかった場合、実引数依存の名前探索は抑制されます。
目次 |
[edit] パラメータ
| first, last | - | 移動する要素の範囲を定義するイテレータ-センチネルペア |
| r | - | 移動する要素の範囲 |
| 結果 | - | コピー先範囲の先頭 |
[edit] 戻り値
{last, result + N}、ここで
1) N = ranges::distance(first, last)。
2) N = ranges::distance(r)。
[edit] 計算量
正確に N 回のムーブ代入。
[edit] 注記
重複する範囲を移動する場合、宛先範囲の開始がソース範囲の外側にある場合はranges::moveが適切ですが、宛先範囲の終了がソース範囲の外側にある場合はranges::move_backwardが適切です。
[edit] 可能な実装
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 {}; |
[edit] 例
以下のコードは、スレッドオブジェクト(それ自体はコピー不能)をあるコンテナから別のコンテナに移動します。
このコードを実行
#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
[edit] 関連項目
| (C++20) |
要素の範囲を逆順で新しい場所にムーブする (アルゴリズム関数オブジェクト) |
| (C++20)(C++20) |
要素の範囲を新しい場所にコピーする (アルゴリズム関数オブジェクト) |
| (C++20) |
要素の範囲を逆順にコピーする (アルゴリズム関数オブジェクト) |
| (C++11) |
要素の範囲を新しい場所にムーブする (関数テンプレート) |
| (C++11) |
引数をxvalueに変換する (関数テンプレート) |