大家主要看一下test02,假设一共10个人,用accumulate求一下平均年龄,该如何实现?
我觉得底层是+=操作,重载了+=号,好像没啥用
#include <iostream>
using namespace std;
#include<vector>
#include<algorithm>
#include<string>
#include<ctime>
#include<numeric>
class Person
{
public:
Person()
{
}
Person(string name, int age);
~Person();
//int operator+=(int x)
//{
// return this->m_Age += x;
//}
Person operator+=(Person tempt)
{
this->m_Age+= tempt.m_Age ;
return *this;
}
private:
string m_Name;
int m_Age;
friend void test02();
friend class MyPrint;
};
Person::Person(string name, int age)
{
this->m_Name = name;
this->m_Age = age;
}
Person::~Person()
{
}
class MyPrint
{
public:
void operator()(const Person& p)
{
cout << "濮撳悕" << p.m_Name << "骞撮緞" << p.m_Age << endl;
}
};
void myPrint(int value)
{
cout << value << " ";
}
void test01()
{
vector<int>v;
for (int i = 0; i < 101; i++)
{
v.push_back(i);
}
cout << "总数"<< endl;
int sum = accumulate(v.begin(), v.end(), 1000);
cout << sum << "\n";
}
void test02()
{
vector<Person>v;
char nameSeed[8][2] = { "A","B","C","D","E", "F", "G", "H" };
srand((unsigned int)time(NULL));
for (int i = 0; i < 8; i++)
{
int age = rand() % 100 + 1;
v.push_back(Person((const char*)nameSeed[i], age));
}
Person pp("C", 0);
Person ppp("D", 9999);
v.push_back(pp);
v.push_back(ppp);
cout << "人员如下 :"<< endl;
for_each(v.begin(), v.end(), MyPrint()); cout << endl;
//int average = accumulate(v.begin(), v.end(), 0) / v.size();
}
int main()
{
test01(); cout << endl;
test02(); cout << endl;
std::cout << "Hello World!\n";
}