C++仿函数

一、概念

仿函数就是一个使用起来像是函数的对象。是在一个类中,operator重载(),该类的对象使用该函数时,就像是一个函数一样。

二、实例代码

template<class T>
class Less {
public:
	bool operator()(const T& x, const T& y) const
	{
		return x < y;
	}
};

void test()
{
	Less<int> func;
	cout << func(1, 2) << endl;
	cout << func.operator()(1, 2) << endl;
	cout << Less<int>()(1, 2) << endl;//匿名对象
	cout << less<int>().operator()(1, 2) << endl;//匿名对象
}
class goods {
public:
	goods(string goodsname,float price,float score)
		:_goodsname(goodsname),
		_price(price),
		_score(score)
	{}
	//获取商品名
	string Get_goodsname() const
	{
		return _goodsname;
	}
	//获取价格
	float Get_price() const
	{
		return _price;
	}
	//获取评分
	float Get_score() const
	{
		return _score;
	}
private:
	string _goodsname;//商品名
	float _price;//价格
	float _score;//评分
};

class goods_price_less {
public:
	bool operator()(const goods& x, const goods& y)//仿函数:低价优先
	{
		return x.Get_price() < y.Get_price();
	}	
};

class goods_price_greater {
public:
	bool operator()(const goods& x, const goods& y)//仿函数:高价优先
	{
		return x.Get_price() > y.Get_price();
	}
};

class goods_score_less {
public:
	bool operator()(const goods& x, const goods& y)//仿函数:低分优先
	{
		return x.Get_score() < y.Get_score();
	}
};

class goods_score_greater {
public:
	bool operator()(const goods& x, const goods& y)//仿函数:高分优先
	{
		return x.Get_score() > y.Get_score();
	}
};

void test()
{
	vector<goods> v;
	v.push_back({ "苹果", 3.2, 3.8 });
	v.push_back({ "香蕉", 2.2, 4.2 });
	v.push_back({ "西瓜", 0.9, 4.9 });

	for (auto& e : v)
	{
		cout << e.Get_goodsname() << " " << e.Get_price() << "元 " << e.Get_score() << "分" << endl;
	}
	cout << endl;

	cout << "低价优先" << endl;
	sort(v.begin(), v.end(), goods_price_less());
	for (auto& e : v)
	{
		cout << e.Get_goodsname() << " " << e.Get_price() << "元 " << e.Get_score() << "分" << endl;
	}
	cout << endl;

	cout << "高价优先" << endl;
	sort(v.begin(), v.end(), goods_price_greater());
	for (auto& e : v)
	{
		cout << e.Get_goodsname() << " " << e.Get_price() << "元 " << e.Get_score() << "分" << endl;
	}
	cout << endl;

	cout << "低分优先" << endl;
	sort(v.begin(), v.end(), goods_score_less());
	for (auto& e : v)
	{
		cout << e.Get_goodsname() << " " << e.Get_price() << "元 " << e.Get_score() << "分" << endl;
	}
	cout << endl;

	cout << "高分优先" << endl;
	sort(v.begin(), v.end(), goods_score_greater());
	for (auto& e : v)
	{
		cout << e.Get_goodsname() << " " << e.Get_price() << "元 " << e.Get_score() << "分" << endl;
	}
	cout << endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

南林yan

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

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

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

打赏作者

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

抵扣说明:

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

余额充值