C++ 优先队列排序规则:运算符重载与仿函数实现
#include
// 方法 1: 运算符重载 struct tmp1 { // 运算符重载 '<' int x; tmp1(int a) { x = a; } bool operator<(const tmp1& a) const { return x < a.x; // 大顶堆 } };
// 方法 2: 重写仿函数 struct tmp2 { // 重写仿函数 bool operator() (tmp1 a, tmp1 b) { return a.x < b.x; // 大顶堆 } };
int main() { tmp1 a(1); tmp1 b(2); tmp1 c(3);
// 使用方法 1
priority_queue<tmp1> d;
d.push(b);
d.push(c);
d.push(a);
while (!d.empty()) {
cout << d.top().x << '\n';
d.pop();
}
cout << endl;
// 使用方法 2
priority_queue<tmp1, vector<tmp1>, tmp2> f;
f.push(c);
f.push(b);
f.push(a);
while (!f.empty()) {
cout << f.top().x << '\n';
f.pop();
}
return 0;
}
// 方法二的解释 方法二中使用了重写仿函数的方式来定义优先队列的排序规则。具体来说,定义了一个结构体 tmp2,并重载了函数调用运算符(),使其成为一个函数对象,即仿函数。在优先队列的定义中,指定了 tmp2 为比较函数对象的类型。
在重载的函数调用运算符中,通过比较 tmp1 对象的 x 成员变量的大小来确定优先级。这里的比较规则是大顶堆,即返回 a.x < b.x。根据这个比较规则,优先队列会按照元素的 x 值从小到大进行排序。
在主函数中,定义了一个优先队列 f,指定了 tmp1 为元素类型,vector
总结一下,方法二中使用重写仿函数的方式来定义优先队列的排序规则,可以通过自定义的比较规则来实现不同的排序方式。
原文地址: https://www.cveoy.top/t/topic/p0CQ 著作权归作者所有。请勿转载和采集!