std::ranges::for_each_n, std::ranges::for_each_n_result
来自 cppreference.cn
定义于头文件 <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 应用于通过 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'}
[编辑] 参见
范围 for 循环(C++11) |
在范围内执行循环 |
(C++20) |
将一元函数对象应用于来自范围的元素 (算法函数对象) |
(C++17) |
将函数对象应用于序列的前 N 个元素 (函数模板) |
将一元函数对象应用于来自范围的元素 (函数模板) |