Namespaces
Variants

std::experimental::ranges:: for_each

From cppreference.net
template < InputIterator I, Sentinel < I > S, class Proj = ranges:: identity ,

IndirectUnaryInvocable < projected < I, Proj >> Fun >
ranges:: tagged_pair < tag:: in ( I ) , tag:: fun ( Fun ) >

for_each ( I first, S last, Fun f, Proj proj = Proj { } ) ;
(1) (ranges TS)
template < InputRange R, class Proj = ranges:: identity ,

IndirectUnaryInvocable < projected < ranges:: iterator_t < R > , Proj >> Fun >
ranges:: tagged_pair < tag:: in ( ranges:: safe_iterator_t < R > ) , tag:: fun ( Fun ) >

for_each ( R && r, Fun f, Proj proj = Proj { } ) ;
(2) (ranges TS)
1) 对范围 [ first , last ) 中的每个迭代器解引用后,将投影函数 proj 的调用结果作为参数,按顺序调用给定的函数对象 f (即执行 ranges:: invoke ( f, ranges:: invoke ( proj, * i ) ) )。
2) (1) 相同,但使用 r 作为源范围,如同使用 ranges:: begin ( r ) 作为 first ,以及 ranges:: end ( r ) 作为 last

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

与其他算法不同,for_each 不允许复制序列中的元素,即使它们是可平凡复制的。

std::for_each (仅要求 MoveConstructible )不同,这些函数要求 Fun 满足 CopyConstructible 概念。

尽管存在上述声明,算法声明的实际模板参数数量和顺序是未指定的。因此,若在调用算法时使用了显式模板参数,该程序很可能不具备可移植性。

目录

参数

first, last - 要应用函数的范围
r - 要应用函数的范围
f - 要应用于范围内每个投影元素的调用对象
proj - 应用于元素的投影

返回值

一个包含以下两个成员的 tagged_pair 对象:

  • 第一个成员,标签为 tag::in ,是源范围的 past-the-end 迭代器(即类型为 I 的迭代器,与哨位 last 比较相等)。
  • 第二个成员,标签为 tag::fun ,从 std::move(f) 初始化(在所有函数对象应用之后)。

复杂度

恰好 last - first 次对 f proj 的应用。

可能实现

template<InputIterator I, Sentinel<I> S, class Proj = ranges::identity,
         IndirectUnaryInvocable<ranges::projected<I, Proj>> Fun>
auto for_each(I first, S last, Fun f, Proj proj = Proj{}) 
    -> ranges::tagged_pair<tag::in(I), tag::fun(Fun)>
{
    for (; first != last; ++first)
        ranges::invoke(f, ranges::invoke(proj, *first));
    return {std::move(first), std::move(f)};
}

示例

参见

对范围内的元素应用函数
(函数模板)
范围 for 循环 (C++11) 在范围上执行循环
范围 中的元素应用一元 函数对象
(函数模板)
(C++17)
对序列的前N个元素应用函数对象
(函数模板)