C++ STL 优先队列使用自定义比较函数的两种方式:重载<符号 或 重载()符号

自定义比较函数的两种方式:

(1)结构体中重载<符号,注意声明函数为const,否则编译不会通过。

bool operator<(const fruit& f1) const
{
	return this->price < f1.price;
}

const修饰的是类函数隐藏的第一个参数 this指针,这表明this指针只读,也即类成员不可修改。

注意该用法只能是成员函数,要是类的静态函数或者是非成员函数就不可以在函数名后面加上const。

如果不声明为const函数,使用friend关键字来标记重载函数也是可行的。

friend bool operator<(const fruit& f1, const fruit& f2)
{
	return f1.price < f2.price;
}

(2)第二种声明自定义比较函数的方式是创建一个结构体,重载()符号,即:

struct cmp
{
	bool operator()(const fruit& f1, const fruit& f2)
	{
		return f1.price > f2.price;
	}
};

使用这种方式后,进行声明优先队列时,需要将此结构体指定给优先队列的比较函数,例如:

priority_queue<fruit, vector<fruit>, cmp> q2; 

注意第三个参数,就是上面声明的结构体名称
第二个参数为容器类型,使用vector<数据类型>即可

以下是完整代码:

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <queue>
using namespace std;

struct fruit
{
	int price;

	// 自定义比较函数的第一种方式:重载<符号
	// 注意此处一定要声明为const,否则编译时无法通过
	// const修饰的是类函数隐藏的第一个参数 this指针,这表明this指针只读,也即类成员不可修改
	// 注意该用法只能是成员函数,要是类的静态函数或者是非成员函数就不可以在函数名后面加上const
	bool operator<(const fruit& f1) const
	{
		return this->price < f1.price;
	}

	// 如果不使用const函数,使用以下友元函数也可行
	/*friend bool operator<(const fruit& f1, const fruit& f2)
	{
		return f1.price < f2.price;
	}*/
};

// 自定义比较函数的第二种方式:结构体
struct cmp
{
	bool operator()(const fruit& f1, const fruit& f2)
	{
		return f1.price > f2.price;
	}
};

int main()
{
	fruit a;
	fruit b;
	fruit c;

	a.price = 11;
	b.price = 12;
	c.price = 4;

	// 第一种方式:结构体内重载<符号
	priority_queue<fruit> q;	
	q.push(a);
	q.push(b);
	q.push(c);
	while (!q.empty())
	{
		cout << "q1 top price = " << q.top().price << endl;
		q.pop();
	}
	cout << "==========================" << endl;

	// 第二种方式:自定义结构体,重载()符号
	priority_queue<fruit, vector<fruit>, cmp> q2; 
	a.price = 3;
	b.price = 2;
	c.price = 7;

	q2.push(a);
	q2.push(b);
	q2.push(c);
	while (!q2.empty())
	{
		cout << "q2 top price = " << q2.top().price << endl;
		q2.pop();
	}

	return 0;
}

运行结果为:

q1 top price = 12
q1 top price = 11
q1 top price = 4
==========================
q2 top price = 2
q2 top price = 3
q2 top price = 7

谢谢阅读

  • 7
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值