Namespaces
Variants

std::ranges:: for_each, std::ranges:: for_each_result

From cppreference.net
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy , ranges::sort , ...
Execution policies (C++17)
Non-modifying sequence operations
Batch operations
(C++17)
Search operations
Modifying sequence operations
Copy operations
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
Removing operations
Order-changing operations
(until C++17) (C++11)
(C++20) (C++20)
Sampling operations
(C++17)

Sorting and related operations
Partitioning operations
Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
Constrained algorithms
All names in this menu belong to namespace std::ranges
Non-modifying sequence operations
Modifying sequence operations
Partitioning operations
Sorting operations
Binary search operations (on sorted ranges)
Set operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Permutation operations
Fold operations
Operations on uninitialized storage
Return types
定义于头文件 <algorithm>
调用签名
template < std:: input_iterator I, std:: sentinel_for < I > S, class Proj = std:: identity ,

std:: indirectly_unary_invocable < std :: projected < I, Proj >> Fun >
constexpr for_each_result < I, Fun >

for_each ( I first, S last, Fun f, Proj proj = { } ) ;
(1) (C++20 起)
template < ranges:: input_range R, class Proj = std:: identity ,

std:: indirectly_unary_invocable <
std :: projected < ranges:: iterator_t < R > , Proj >> Fun >
constexpr for_each_result < ranges:: borrowed_iterator_t < R > , Fun >

for_each ( R && r, Fun f, Proj proj = { } ) ;
(2) (C++20 起)
辅助类型
template < class I, class F >
using for_each_result = ranges:: in_fun_result < I, F > ;
(3) (C++20 起)
1) 将给定的函数对象 f 按顺序应用于范围 [ first , last ) 中每个迭代器投影的值的计算结果。
2) (1) 相同,但使用 r 作为源范围,如同使用 ranges:: begin ( r ) 作为 first ,以及 ranges:: end ( r ) 作为 last

对于两个重载版本,若迭代器类型为可变类型, f 可通过解引用迭代器修改范围内的元素。若 f 返回结果,该结果将被忽略。

本页面描述的函数式实体是 算法函数对象 (非正式称为 niebloids ),即:

目录

参数

first, last - 定义要应用函数的元素范围的 迭代器-哨位
r - 要应用函数的元素范围
f - 应用于投影范围的函数
proj - 应用于元素的投影

返回值

{ ranges:: next ( std :: move ( first ) , last ) , std :: move ( f ) }

复杂度

恰好应用 ranges:: distance ( first, last ) f proj

可能的实现

struct for_each_fn
{
    template<std::input_iterator I, std::sentinel_for<I> S, class Proj = std::identity,
             std::indirectly_unary_invocable<std::projected<I, Proj>> Fun>
    constexpr ranges::for_each_result<I, Fun>
        operator()(I first, S last, Fun f, Proj proj = {}) const
    {
        for (; first != last; ++first)
            std::invoke(f, std::invoke(proj, *first));
        return {std::move(first), std::move(f)};
    }
    template<ranges::input_range R, class Proj = std::identity,
             std::indirectly_unary_invocable<std::projected<ranges::iterator_t<R>,
             Proj>> Fun>
    constexpr ranges::for_each_result<ranges::borrowed_iterator_t<R>, Fun>
        operator()(R&& r, Fun f, Proj proj = {}) const
    {
        return (*this)(ranges::begin(r), ranges::end(r), std::move(f), std::ref(proj));
    }
};
inline constexpr for_each_fn for_each;

示例

以下示例使用 lambda表达式 递增vector中的所有元素,然后使用仿函数中重载的 operator() 计算它们的和。注意,为计算总和,建议使用专用算法 std::accumulate

#include <algorithm>
#include <cassert>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
struct Sum
{
    void operator()(int n) { sum += n; }
    int sum {0};
};
int main()
{
    std::vector<int> nums {3, 4, 2, 8, 15, 267};
    auto print = [](const auto& n) { std::cout << ' ' << n; };
    namespace ranges = std::ranges;
    std::cout << "before:";
    ranges::for_each(std::as_const(nums), print);
    print('\n');
    ranges::for_each(nums, [](int& n) { ++n; });
    // calls Sum::operator() for each number
    auto [i, s] = ranges::for_each(nums.begin(), nums.end(), Sum());
    assert(i == nums.end());
    std::cout << "after: ";
    ranges::for_each(nums.cbegin(), nums.cend(), print);
    std::cout << "\n" "sum: " << s.sum << '\n';
    using pair = std::pair<int, std::string>; 
    std::vector<pair> pairs {{1,"one"}, {2,"two"}, {3,"tree"}};
    std::cout << "project the pair::first: ";
    ranges::for_each(pairs, print, [](const pair& p) { return p.first; });
    std::cout << "\n" "project the pair::second:";
    ranges::for_each(pairs, print, &pair::second);
    print('\n');
}

输出:

before: 3 4 2 8 15 267 
after:  4 5 3 9 16 268
sum: 305
project the pair::first:  1 2 3
project the pair::second: one two tree

参见

范围 for 循环 (C++11) 在范围上执行循环
对一系列元素应用函数
(算法函数对象)
对序列的前N个元素应用函数对象
(算法函数对象)
对来自 范围 的元素应用一元 函数对象
(函数模板)