【C++】仿函数的定义与使用

一.定义

        仿函数是类中定义了一个含有operator ()成员函数的对象,可以将它视为一般的函数,它有着快捷调用的功能——通过仿函数地址调用,其次,它相比一般函数可以传入模板参数,适配与各种模板的使用中。

二.使用

1.作为类的模板参数适配于各种模板类的调用

        最常见的就是比较大小,在优先级队列priority_queue中就有仿函数less和greater,以下代码模拟实现两种仿函数的功能:

// 仿函数比较
template<class T>
class Less
{
public:
	bool operator()(const T& a, const T& b)
	{
		return a < b;
	}
};

template<class T>
class Greater
{
public:
	bool operator()(const T& a, const T& b)
	{
		return a > b;
	}
};

        将模板类设置为与调用类中的模板类型相同,可以达到比较大小的效果,同时如果我们将priority_queue传入不同的仿函数,将有不同的效果——默认仿函数为less,传入greater则可以达到建大堆的效果。

template<class T, class Container = vector<T>, class cmp = Less<T>>
class priority_queue

2.自定义仿函数

        有的情况下我们必须要自定义仿函数,比如如果我们传入的模板类型为自定义类型的指针;此处拿日期类作为例子:如果继续使用上述的仿函数比较,那么最终比较的将是日期类的指针优先级,显然,这是毫无意义的。

class Date
{
public:
	Date(int year = 1900, int month = 1, int day = 1)
		: _year(year)
		, _month(month)
		, _day(day)
	{}

	bool operator<(const Date& d)const
	{
		return (_year < d._year) ||
			(_year == d._year && _month < d._month) ||
			(_year == d._year && _month == d._month && _day < d._day);
	}

	bool operator>(const Date& d)const
	{
		return (_year > d._year) ||
			(_year == d._year && _month > d._month) ||
			(_year == d._year && _month == d._month && _day > d._day);
	}

	friend ostream& operator<<(ostream& _cout, const Date& d);
private:
	int _year;
	int _month;
	int _day;
};

ostream& operator<<(ostream& _cout, const Date& d)
{
	_cout << d._year << "-" << d._month << "-" << d._day;
	return _cout;
}

         此时我们可以自定义该类的仿函数如下:

// 自定义仿函数
struct LessPDate
{
	// struct结构体默认权限为public
	bool operator()(const Date* p1, const Date* p2)
	{
		return *p1 < *p2;
	}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Evea_来自深渊

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

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

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

打赏作者

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

抵扣说明:

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

余额充值