#include \n#include \nusing namespace std;

//方法1\nstruct tmp1 //运算符重载<\n{\n int x;
tmp1(int a) {x = a;}
bool operator<(const tmp1& a) const
{
return x < a.x; //大顶堆
}
}

//方法2\nstruct tmp2 //重写仿函数\n{
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, tmp2> f;
f.push(c);
f.push(b);
f.push(a);
while (!f.empty())
{
cout << f.top().x << '\n';
f.pop();
}
}方法二我不太理解内容:方法二是通过重写仿函数(即重载函数调用运算符)来定义优先队列的排序规则。在方法二中,定义了一个名为tmp2的结构体,其中重载了函数调用运算符。在函数调用运算符中,通过比较tmp1结构体对象的x成员来确定排序规则,即返回a.x < b.x,表示大顶堆。然后在定义优先队列时,使用了tmp1作为元素类型,vector作为容器类型,tmp2作为排序规则类型。通过这种方式,实现了自定义的排序规则。最后按照定义的排序规则,对优先队列进行操作,并输出结果。

C++ 优先队列自定义排序规则:运算符重载与仿函数

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

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