来自cppreference.com
| 在标头 <algorithm> 定义
|
||
| 调用签名 |
||
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>
for_each_n( I first, std::iter_difference_t<I> count,
Fun f, Proj proj = {} );
|
(1) | (C++20 起) |
template< /*execution-policy*/ Ep,
std::random_access_iterator I, class Proj = identity,
std::indirectly_unary_invocable<std::projected<I, Proj>> Fun >
I for_each_n( Ep&& policy, I first, iter_difference_t<I> count,
Fun f, Proj proj = {} );
|
(2) | (C++26 起) |
| 辅助类型 |
||
template< class I, class F >
using for_each_n_result = ranges::in_fun_result<I, F>;
|
(3) | (C++20 起) |
/*execution-policy*/ 的定义见此页。
对目标范围 [first, ranges::next(first, count)) 中的每个(以 proj 投影后的)元素应用给定的可调用对象 f。忽略 f 返回的结果。
1) 从
first 开始按顺序应用 f。2) 不一定按顺序应用
f。按照 policy 执行算法。 与其他并行算法不同,
for_each_n 不能任意复制目标范围中的元素。如果 count >= 0 不是 true ,那么行为未定义。
此页面上描述的函数式实体是算法函数对象(非正式地称为 niebloid),即:
参数
| first | - | 目标范围的起始 |
| count | - | 目标范围的元素个数 |
| f | - | 会应用到(投影后的)元素的可调用对象 |
| proj | - | 会应用到元素的投影 |
| policy | - | 所用的执行策略 |
返回值
1)
{ranges::next(first, count), std::move(f)}2)
ranges::next(first, count)复杂度
应用 count 次 f 与 proj。
可能的实现
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> count,
Fun fun, Proj proj = Proj{}) const
{
for (; count-- > 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, const auto& 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);
// 对前三个数取相反数:
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);
// 用投影对数据成员 “pair::first” 取相反数:
std::ranges::for_each_n(s.begin(), 2, [](auto& x) { x *= -1; }, &P::first);
print("s", s);
// 用投影大写化数据成员 “pair::second”:
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'}
参阅
(C++17) |
应用函数对象到序列的前 N 个元素 (函数模板) |
| 应用一元函数对象到范围中的元素 (函数模板 & 算法函数对象) | |
(C++20) |
|
范围 for 循环 (C++11)
|
执行范围上的循环 |