std::for_each
来自cppreference.com
                    
                                        
                    
                    
                                                            
                    | 
   | 
  该页由英文版wiki使用Google Translate机器翻译而来。 
 该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里.  | 
|   在头文件 <algorithm> 中定义
   | 
||
|   template< class InputIt, class UnaryFunction > UnaryFunction for_each( InputIt first, InputIt last, UnaryFunction f );  | 
||
将给定的函数f的结果运用在从[first, last)每一个迭代器所指向的内容,依照顺序。 如果InputIt是一个可变的迭代器,f可以通过解引用迭代器来修改处于范围内的元素。如果f返回一个结果,该结果将被忽略.
目录 | 
[编辑] 参数
| first, last | - |    的范围内应用的功能 
 | 
| f | - |    一元函数对象  
原文:  the unary function object to be applied   | 
| 类型要求 | ||
 -InputIt 必须满足 InputIterator 的要求。
 | ||
 -UnaryFunction 必须满足 MoveConstructible 的要求。 Does not have to be CopyConstructible
 | ||
[编辑] 返回值
f. (至 C++11)
std::move(f). (C++11 起)
[编辑] 复杂度
精确的(last - first)(即f的大小)的复杂度
[编辑] 可能的实现
template<class InputIt, class UnaryFunction> UnaryFunction for_each(InputIt first, InputIt last, UnaryFunction f) { for (; first != last; ++first) { f(*first); } return f; }  | 
[编辑] 示例
 下面的示例使用了lambda函数递增一个向量的所有元素,然后计算它们的总和:
 
原文:
 The following example uses a lambda函数 to increment all of the elements of a vector and then computes a sum of them:
 
#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, 9, 15, 267}; std::cout << "before: "; for (auto n : nums) { std::cout << n << " "; } std::cout << '\n'; std::for_each(nums.begin(), nums.end(), [](int &n){ n++; }); Sum s = std::for_each(nums.begin(), nums.end(), Sum()); std::cout << "after: "; for (auto n : nums) { std::cout << n << " "; } std::cout << '\n'; std::cout << "sum: " << s.sum << '\n'; }
输出:
before: 3 4 2 9 15 267 after: 4 5 3 10 16 268 sum: 306
[编辑] 另请参阅
|    将一个函数应用于某一范围的元素   (函数模板)  | |
| 范围的循环 |    执行循环范围(C++11 起)  
 |