函数原型
UnaryProc for_each (InputIterator beg, InputIterator end, UnaryProc op)
* 调用 op(elem), [begin, end)区间的每一个元素
* 返回遍历执行后的op副本
* op可能修改元素, 与transform算法相似
* op的返回值将被忽略
* 算法复杂度: 线性, 每个元素都调用一次op
一、基本用法
1. 用lambda作为op
int main()
{
vector<int> coll;
INSERT_ELEMENTS(coll,1,9); // 插入1到9
// 打印每个元素
for_each (coll.cbegin(), coll.cend(),
[](int elem){
cout << elem << ’ ’;
});
cout << endl;
}
2. 普通函数作为op
void print(int elem) { cout << elem << ' '; }
for_each(coll.begin(), coll.end(), print);
3. 函数对象作为op
template <typename T>
class AddValue
{
private:
T theValue;
public:
AddValue(const T& v) : theValue(v) {}
void operator() (T& elem) const
{
elem += theValue; // 元素加上一个值
}
}
for_each (coll.begin(), coll.end(), AddValue<int>(10));
二、其他说明
1. C++11基于范围的for循环遍历每个元素更方便
for (auto elem : coll)
{
cout << elem << ' ';
}
2. 可以利用for_each的返回值
class MeanValue
{
private:
long num, sum;
public:
MeanValue() : num(0), sum(0) {}
void operator() (int elem)
{
num++;
sum += elem;
}
operator double()
{
return static_cast<double>(sum) / static_cast<double>(num);
}
};
double mv = for_each(coll.begin(), coll.end(), MeanValue());
cout << "mean value: " << mv << endl;