std::ranges::for_each_n, std::ranges::for_each_n_result
来自cppreference.com
<tbody>
</tbody>
| 在标头 <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> n, Fun f, Proj proj = {}); |
(1) | (C++20 起) |
| 辅助类型 |
||
template< class I, class F > using for_each_n_result = ranges::in_fun_result<I, F>; |
(2) | (C++20 起) |
1) 按顺序,对范围
[first, first + n) 中的每个迭代器进行解引用并以proj 投影的结果,应用给定的函数对象 f。若迭代器类型可变,则 f 可能通过解引用的迭代器修改范围中的元素。若 f 返回了结果,则忽略该结果,若 n 小于零,则行为未定义。
此页面上描述的函数式实体是算法函数对象(非正式地称为 niebloid),即:
参数
| first | - | 代表要应用函数到的范围起始的迭代器 |
| n | - | 要应用函数的元素数 |
| f | - | 应用到投影后范围 [first, first + n) 的函数
|
| proj | - | 应用到元素的投影 |
返回值
对象 {first + n, std::move(f)},其中 first + n 可能求值为 std::ranges::next(std::move(first), n),取决于迭代器类别。
复杂度
准确 n 次应用 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> 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);
// 对前三个数取相反数:
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'}
参阅
范围 for 循环 (C++11)
|
执行范围上的循环 |
(C++20) |
应用一元函数对象到范围中元素 (算法函数对象) |
(C++17) |
应用函数对象到序列的前 N 个元素 (函数模板) |
| 应用一元函数对象到范围中元素 (函数模板) |