引用了部分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;
}