C++STL算术类函数对象

STL算术类函数对象

什么是函数对象?
函数对象可以简单理解为:

  1. 重载函数操作符“()"的类,这种类的对象,称为函数对象。
  2. 它是行为类似函数的对象,又称仿函数。
算术类函数对象的种类
// 加
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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林多

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值