STL算术类函数对象
什么是函数对象?
函数对象可以简单理解为:
- 重载函数操作符“()"的类,这种类的对象,称为函数对象。
- 它是行为类似函数的对象,又称仿函数。
算术类函数对象的种类
// 加
std::plus<T>;
// 减
std::minux<T>;
// 乘
std::multiplies<T>;
// 除
std::divides<T>;
// 模
std::modulus<T>;
// 负
std::negate<T>;
内置类型使用STL算术类函数对象
- 由于C++内置类型,已有对应"±*/%"几种运算的处理。所以直接调用即可。
- 对于自定义类型,需要根据需要重载相应运算符。
- 例:内置类型使用STL算术类函数对象
#include <functional>
#include <iostream>
int main()
{
std::plus<int> plusObj;
std::minus<int> minusObj;
std::multiplies<int> mulObj;
std::divides<int> divObj;
std::modulus<int> modObj;
std::negate<int> negObj;
// You can call it by temporary object
// std::cout << std::plus<int>()(1,2) << std::endl;
std::cout << plusObj(1, 2) << std::endl;
std::cout << minusObj(1, 2) << std::endl;
std::cout << mulObj(1, 2) << std::endl;
std::cout << divObj(2, 1) << std::endl;
std::cout << modObj(2, 1) << std::endl;
std::cout << negObj(1) << std::endl;
return 0;
}
自定义类型使用STL算术类函数
- 对于C++自定义类型,需要重载其运算符。
- 例:复数操作类,使用STL算术类函数对象。
#include <functional>
#include <iostream>
#include <vector>
#include <numeric>
class Complex
{
public:
Complex()
{
this->real = 0.0;
this->virt = 0.0;
}
Complex(float real, float virt)
{
this->real = real;
this->virt = virt;
}
void show()
{
std::cout << real << "+" << virt << "i" << std::endl;;
}
Complex operator+(const Complex&c) const
{
Complex result;
result.real = this->real + c.real;
result.virt = this->virt + c.virt;
return result;
}
private:
double real;
double virt;
};
int main()
{
Complex c1(1.0, 2.0);
Complex c2(3.0, 4.0);
Complex c3 = c1 + c2;
Complex result = std::plus<Complex>()(c1, c2);
result.show();
Complex c;
std::vector<Complex> v;
v.push_back(c1);
v.push_back(c2);
v.push_back(c3);
v.push_back(result);
Complex vectorResult = std::accumulate(v.begin(), v.end(), c);
vectorResult.show();
return 0;
}