首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::for_each

Defined in header <algorithm>

?

?

template< class InputIt, class UnaryFunction > UnaryFunction for_each( InputIt first, InputIt last, UnaryFunction f );

(1)

?

template< class ExecutionPolicy, class ForwardIt, class UnaryFunction2 > void for_each( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, UnaryFunction2 f );

(2)

(since C++17)

1%29应用给定的函数对象f对范围内的每个迭代器取消引用的结果。[first, last),按顺序排列。

2%29应用给定的函数对象f对范围内的每个迭代器取消引用的结果。[first, last)%28不一定按%29顺序排列。该算法是根据policy此重载不参与过载解决,除非std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>是真的。

对于这两个重载,如果迭代器类型是可变的,f可以通过取消引用的迭代器修改范围的元素。如果f返回一个结果,结果将被忽略。

与其他算法不同,对于[医]每个元素都不允许复制序列中的元素,即使它们是微不足道的可复制的。

参数

first, last

-

the range to apply the function to

policy

-

the execution policy to use. See execution policy for details.

f

-

function object, to be applied to the result of dereferencing every iterator in the range [first, last) The signature of the function should be equivalent to the following: void fun(const Type &a); The signature does not need to have const &. The type Type must be such that an object of type InputIt can be dereferenced and then implicitly converted to Type. ?

类型要求

-输入必须符合输入器的要求。

---。

-单一功能必须符合可移动建筑的要求。不一定是可复制的

-单一功能2必须符合CopyConstrucable的要求。

返回值

1%29f%28直到C++11%29std::move(f)%28自C++11%29

2%29%28Nothing%29

复杂性

一点儿没错last---first的应用f...

例外

带有名为ExecutionPolicy报告错误如下:

  • 如果执行作为算法一部分调用的函数,则引发异常ExecutionPolicy是其中之一标准政策,,,std::terminate叫做。对于任何其他人ExecutionPolicy,行为是由实现定义的。
  • 如果算法不能分配内存,std::bad_alloc被扔了。

可能的实施

模板<类Inputit,类UnaryFunction>UnaryFunction[医]每%28输入第一,输入最后,单功能f%29{%28;第1%21=最后;++第29%(f%28)%2A第一%29;}返回f;}

*。

下面的示例使用Lambda函数增加向量的所有元素,然后使用重载operator()在函子中计算它们的和:

二次

代码语言:javascript
复制
#include <vector>
#include <algorithm>
#include <iostream>
 
struct Sum
{
    Sum(): sum{0} { }
    void operator()(int n) { sum += n; }
    int sum;
};
 
int main()
{
    std::vector<int> nums{3, 4, 2, 8, 15, 267};
 
    auto print = [](const int& n) { std::cout << " " << n; };
 
    std::cout << "before:";
    std::for_each(nums.begin(), nums.end(), print);
    std::cout << '\n';
 
    std::for_each(nums.begin(), nums.end(), [](int &n){ n++; });
 
    // calls Sum::operator() for each number
    Sum s = std::for_each(nums.begin(), nums.end(), Sum());
 
    std::cout << "after: ";
    std::for_each(nums.begin(), nums.end(), print);
    std::cout << '\n';
    std::cout << "sum: " << s.sum << '\n';
}

二次

产出:

二次

代码语言:javascript
复制
before: 3 4 2 8 15 267
after:  4 5 3 9 16 268
sum: 305

二次

另见

transform

applies a function to a range of elements (function template)

range-for loop

executes loop over range (since C++11)

for_each_n (C++17)

applies a function object to the first n elements of a sequence (function template)

代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com