template<typename InputIterator, typename Function>
Function for_each(InputIterator beg, InputIterator end, Function f) {
while(beg != end)
f(*beg++);
}
所以在STL标准模版库中p301-p302中
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class MeanValue{
private:
long num;
long sum;
public:
MeanValue():num(0),sum(0){
}
void operator()(int elem){
num++;
sum+=elem;
}
double value(){
return static_cast<double>(sum)/static_cast<double>(num);
}
};
int main()
{
vector<int> coll;
for(int i=1;i<=8;++i){
coll.push_back(i);
}
MeanValue mv=for_each(coll.begin(),coll.end(),MeanValue());
cout<<"mean value: "<<mv.value()<<endl;
system("pause");
}
这里得出4.5,
MeanValue mv=for_each(coll.begin(),coll.end(),MeanValue());
在for_each中,MeanValue()就变成了MeanValue(*beg++);从而调用仿函数