自定义比较函数的两种方式:
(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
谢谢阅读