Example
#include <vector>
#include <functional>
#include <iostream>
#include <algorithm>
using namespace std;
class summaryInfo{
public:
summaryInfo():nsum(0),ncount(0){}
int getSum(){ return nsum; }
int getMin(){ return nmin; }
int getMax(){ return nmax; }
int getNum(){ return ncount; }
void operator()(int x){
if(ncount==0){
nmax = x;
nmin = x;
}else{
if(nmax < x){
nmax = x;
}
if(nmin > x){
nmin = x;
}
}
nsum += x;
ncount++;
}
private:
int nsum;
int nmin;
int nmax;
int ncount;
};
int main(){
vector<int> v({1,4,2,8,5,7});
summaryInfo s = for_each(v.begin(), v.end(), summaryInfo());
cout << "Max number: " << s.getMax() << endl;
cout << "Min number: " << s.getMin() << endl;
cout << "Average: " << static_cast<double>(s.getSum())/static_cast<double>(v.size()) << endl;
return 0;
}
for_each takes three parameters, v.begin() and v.end() are begin and end of range, it is an open interval, [begin, end). The third parameter is a function objector. for_each will return the function objector, therefore, by changing its state, we could get return value from for_each. Using template method, the above example could be rewritten as follows
#include <vector>
#include <functional>
#include <iostream>
#include <algorithm>
using namespace std;
template <class T>
class summaryInfo{
public:
summaryInfo():nsum(0),ncount(0){}
T getSum(){ return nsum; }
T getMin(){ return nmin; }
T getMax(){ return nmax; }
int getNum(){ return ncount; }
void operator()(T x){
if(ncount==0){
nmax = x;
nmin = x;
}else{
if(nmax < x){
nmax = x;
}
if(nmin > x){
nmin = x;
}
}
nsum += x;
ncount++;
}
private:
T nsum;
T nmin;
T nmax;
int ncount;
};
int main(){
vector<int> v({1,4,2,8,5,7});
summaryInfo<int> s = for_each(v.begin(), v.end(), summaryInfo<int>());
cout << "Max number: " << s.getMax() << endl;
cout << "Min number: " << s.getMin() << endl;
cout << "Average: " << static_cast<double>(s.getSum())/static_cast<double>(v.size()) << endl;
return 0;
}