《C++STL基础及应用》
#include <iostream>
#include<functional>
#include<vector>
#include <numeric>
using namespace std;
//非常规数据类型基本对象的使用
//复数
class Complex
{
public:
float real;
float virt;
public:
Complex()
{
this->real=0.0f;
this->virt=0.0f;
}
Complex(float real,float virt)
{
this->real=real;
this->virt=virt;
}
//前面使用const 表示返回值为const
//后面加 const表示函数不可以修改class的成员,即加号前面的类的成员变量固定
Complex operator+(const Complex & c)const
{
Complex v;
v.real=real +c.real;
v.virt=virt+ c.virt;
return v;
}
};
int main()
{
Complex c1(1,2);
Complex c2(3,4);
Complex c3=c1+c2;
Complex c4=plus<Complex>()(c1,c2);
cout<<c3.real<<"+"<<c3.virt<<"i"<<endl;
cout<<c4.real<<"+"<<c4.virt<<"i"<<endl;
vector<Complex> v;
//用到 Complex(),c就相当于sum=0;
Complex c;
v.push_back(c1);
v.push_back(c2);
v.push_back(c3);
v.push_back(c4);
//使用accumulate求和
Complex result=accumulate(v.begin(),v.end(), c,plus<Complex>());
cout<<result.real<<"+"<<result.virt<<"i"<<endl;
}