for_each

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值