C++ 优先级队列的排序问题

大大的道道的 2017-03-10 01:35:49
为什么不能写成指针的形式,会提示语法错误?
#include <iostream>
#include <queue>
using namespace std;

class T {
public:
int x, y, z;
T(int a, int b, int c):x(a), y(b), z(c)
{
}
};
bool operator < (const T* &t1, const T* &t2)
{
return t1->z > t2->z;
}
int main()
{
priority_queue<T*> q;
q.push(&T(4,4,3));
q.push(&T(2,2,5));
q.push(&T(1,5,4));
q.push(&T(3,3,6));
while (!q.empty())
{
T* t = q.top();
q.pop();
cout << t->x << " " << t->y << " " << t->z << endl;
}
return 1;
}





写成这样的就可以了

#include <iostream>
#include <queue>
using namespace std;

class T {
public:
int x, y, z;
T(int a, int b, int c):x(a), y(b), z(c)
{
}
};
bool operator < (const T &t1, const T &t2)
{
return t1.z > t2.z; // 按照z的顺序来决定t1和t2的顺序
}
int main()
{
priority_queue<T> q;
q.push(T(4,4,3));
q.push(T(2,2,5));
q.push(T(1,5,4));
q.push(T(3,3,6));
while (!q.empty())
{
T t = q.top();
q.pop();
cout << t.x << " " << t.y << " " << t.z << endl;
}
return 1;
}
...全文
239 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
大大的道道的 2017-03-10
  • 打赏
  • 举报
回复
@paschen 多谢 , 刚查了下资料, 的确是这样的。 你这样一说就更清楚了。。。 http://blog.csdn.net/senyelicone/article/details/51850284
paschen 版主 2017-03-10
  • 打赏
  • 举报
回复
类对象才能重载operator < 你不能为两个指针去重载operator <,指针本身就有内置的operator <进行比较

65,184

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧