#include #include using namespace std;

// 方法 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); priority_queue d; d.push(b); d.push(c); d.push(a); while (!d.empty()) { cout << d.top().x << '\n'; d.pop(); } cout << endl;

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();
}

} 这个方法二我不太理解内容:方法二使用了自定义的仿函数 tmp2,它重载了函数调用运算符 operator(),接受两个参数 tmp1 a 和 tmp1 b,然后比较它们的 x 值,并返回比较结果。

在方法二中,priority_queue 的第三个参数是一个自定义的比较函数对象,用于确定元素的顺序。传入 tmp2 对象 f 作为比较函数对象,它会按照 f(a, b) 的结果来确定 a 和 b 在堆中的顺序。

在这里,tmp2 的比较函数实现的是小顶堆,即通过返回 a.x < b.x 来确定元素的顺序。所以当执行 f.push(c)、f.push(b) 和 f.push(a) 时,元素会按照 x 值从小到大的顺序插入堆中。

最后,通过循环输出 f.top().x,可以看到元素被按照 x 值从小到大的顺序输出。

C++ 优先队列 (priority_queue) 的两种自定义比较方式

原文地址: https://www.cveoy.top/t/topic/p0CO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录