std::for_each的标准调用方式为:
template<class InputIt, class UnaryFunc>
constexpr UnaryFunc for_each(InputIt first, InputIt last, UnaryFunc f)
{
for (; first != last; ++first)
f(*first);
return f; // implicit move since C++11
}
前两个参数分别表示遍历容器迭代器的开始和结束位置,而第三个参数是针对每个遍历成员的调用函数f,当然调用函数f也可以通过lambda调用来实现,下面通过实例来说明:
#include <vector>
#include <algorithm>
#include <iostream>
struct Sum {
Sum() { sum = 0; }
void operator()(int n) { sum += n; }
int sum;
};
struct student {
int age;
int num;
};
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 << std::endl;
int age_sum = 0, num_sum = 0;
std::vector<student> stus = {{1,2},{2,3},{3,4},{4,5}};
std::for_each(stus.begin(), stus.end(), [&](student& stu) {
age_sum += stu.age;
num_sum += stu.num;
});
std::cout << "age sum is " << age_sum << std::endl;
std::cout << "num sum is " << num_sum << std::endl;
}
输出结果:
before: 3 4 2 9 15 267
after: 4 5 3 10 16 268
age sum is 10
num sum is 14
比较容易理解,需要注意的就是函数调用传入的是每个迭代器的成员,故函数参数类型要与之对应。