std::ranges::for_each_n, std::ranges::for_each_n_result
From cppreference.com
| ヘッダー <algorithm> で定義 |
||
| 呼び出しシグネチャ |
||
| template< std::input_iterator I, class Proj = std::identity, std::indirectly_unary_invocable<std::projected<I, Proj>> Fun > |
(1) | (C++20以降) |
| ヘルパー型 |
||
| template< class I, class F > using for_each_n_result = ranges::in_fun_result<I, F>; |
(2) | (C++20以降) |
1) 指定された関数オブジェクト f を、イテレータ範囲
[first, first + n) の各イテレータの逆参照を proj によって射影した結果に、順に適用します。イテレータ型がミュータブルである場合、f は逆参照されたイテレータを通じて範囲の要素を変更する可能性があります。f が結果を返す場合、その結果は無視されます。n が負の場合、動作は未定義です。
このページで説明されている関数のようなエンティティは、アルゴリズム関数オブジェクト(非公式にはニーブロイドとして知られている)です。つまり、
- これらのいずれかを呼び出す際に、明示的なテンプレート引数リストを指定することはできません。
- これらのいずれも実引数依存の名前探索には見えません。
- これらのいずれかが関数呼び出し演算子の左側の名前として通常の非修飾名探索によって見つかった場合、実引数依存の名前探索は抑制されます。
目次 |
[編集] パラメータ
| first | - | 関数を適用する範囲の先頭を示すイテレータ |
| n | - | 関数を適用する要素数 |
| f | - | 範囲 [first, first + n) の射影された要素に適用する関数 |
| proj | - | 要素に適用する射影 |
[編集] 戻り値
{first + n, std::move(f)} のオブジェクト。ここで first + n は、イテレータのカテゴリに応じて std::ranges::next(std::move(first), n) と評価される場合があります。
[編集] 計算量
f および proj の正確に n 回の適用。
[編集] 実装例
struct for_each_n_fn { template<std::input_iterator I, class Proj = std::identity, std::indirectly_unary_invocable<std::projected<I, Proj>> Fun> constexpr for_each_n_result<I, Fun> operator()(I first, std::iter_difference_t<I> n, Fun fun, Proj proj = Proj{}) const { for (; n-- > 0; ++first) std::invoke(fun, std::invoke(proj, *first)); return {std::move(first), std::move(fun)}; } }; inline constexpr for_each_n_fn for_each_n {};
[編集] 例
このコードを実行
#include <algorithm> #include <array> #include <iostream> #include <ranges> #include <string_view> struct P { int first; char second; friend std::ostream& operator<<(std::ostream& os, const P& p) { return os << '{' << p.first << ",'" << p.second << "'}"; } }; auto print = [](std::string_view name, auto const& v) { std::cout << name << ": "; for (auto n = v.size(); const auto& e : v) std::cout << e << (--n ? ", " : "\n"); }; int main() { std::array a {1, 2, 3, 4, 5}; print("a", a); // Negate first three numbers: std::ranges::for_each_n(a.begin(), 3, [](auto& n) { n *= -1; }); print("a", a); std::array s { P{1,'a'}, P{2, 'b'}, P{3, 'c'}, P{4, 'd'} }; print("s", s); // Negate data members 'P::first' using projection: std::ranges::for_each_n(s.begin(), 2, [](auto& x) { x *= -1; }, &P::first); print("s", s); // Capitalize data members 'P::second' using projection: std::ranges::for_each_n(s.begin(), 3, [](auto& c) { c -= 'a'-'A'; }, &P::second); print("s", s); }
出力
a: 1, 2, 3, 4, 5
a: -1, -2, -3, 4, 5
s: {1,'a'}, {2,'b'}, {3,'c'}, {4,'d'}
s: {-1,'a'}, {-2,'b'}, {3,'c'}, {4,'d'}
s: {-1,'A'}, {-2,'B'}, {3,'C'}, {4,'d'}[編集] 関連項目
範囲forループ(C++11) |
範囲に対するループを実行する |
| (C++20) |
範囲内の要素に単項関数オブジェクトを適用する (アルゴリズム関数オブジェクト) |
| (C++17) |
シーケンスの最初のN個の要素に関数オブジェクトを適用する (関数テンプレート) |
| 範囲内の要素に単項関数オブジェクトを適用する (関数テンプレート) |