函数对象-如何保留结果状态

引用了部分c++标准库一书的代码

#include<iostream>
#include<functional>
#include<algorithm>
#include<typeinfo>
#include<vector>
#include<assert.h>
using namespace std;


class MeanValue
{
public:
    MeanValue():m_count(0),m_total(0){}
    void operator()(int elem)
    {
        ++m_count;
        m_total += elem;
    }

    double theAverageValue()
    {
        assert(m_count != 0);
        return static_cast<double>(m_total) / static_cast<double>(m_count);
    }
    MeanValue(MeanValue&other)//如果只有复制构造,就调用复制构造函数;
    {
        cout << "copy construction" << endl;
        this->m_count = other.m_count;
        this->m_total = other.m_total;
    }
    MeanValue(MeanValue&&other)//如果有复制构造和移动构造,优先调用移动构造->在for_each返回一个临时对象,并用这个临时对象构造一个新的对象的时候;
    {
        cout << "move construction" << endl;
        this->m_count = std::move(other.m_count);
        this->m_total = std::move(other.m_total);
    }
private:
    long m_count;
    long m_total;

};

int main()
{
    vector<int> v1{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    //方法一
    MeanValue calc=for_each(v1.begin(), v1.end(), MeanValue()); //传临时对象进入计算;然后临时对象返回时,用一个新的对象接收——移动构造或复制构造;
    cout << calc.theAverageValue() << endl;

    //方法二
    MeanValue me;
    for_each(v1.begin(), v1.end(), std::ref(me));    //传引用进入计算;
    cout << me.theAverageValue() << endl;

    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值