std::ranges::for_each_n, std::ranges::for_each_n_result
來自 cppreference.com
定義於標頭檔案 <algorithm> |
||
呼叫簽名 (Call signature) |
||
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 應用於透過 proj 投影的、對範圍
[
first,
first + n)
中每個迭代器解引用後的結果,按順序執行。如果迭代器型別是可變的,f 可以透過解引用後的迭代器修改範圍中的元素。如果 f 返回結果,該結果將被忽略。如果 n 小於零,則行為未定義。
本頁描述的類函式實體是 演算法函式物件(非正式地稱為 niebloids),即
目錄 |
[編輯] 引數
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'}
[編輯] 參閱
range-for 迴圈(C++11) |
對範圍執行迴圈 |
(C++20) |
對範圍中的元素應用一元函式物件 (演算法函式物件) |
(C++17) |
對序列中的前 N 個元素應用函式物件 (函式模板) |
對範圍中的元素應用一元函式物件 (函式模板) |