自定义类的Priority Queue排序问题【急】

ScytheV 2012-02-09 01:00:59
我有一个自定义的类叫Cell,里面有float类型的成员变量叫fValue。Priority Queue的类型也是Cell,我想每次push Priority Queue的时候他都可以按照里面元素的fValue值来排序。于是我重载了Cell类的运算符:

bool operator<(Cell const& x, Cell const& y);
bool operator>(Cell const& x, Cell const& y);

bool operator<(Cell const& x, Cell const& y) {
if(x.fValue < y.fValue) {
return true;
} else {
return false;
}
};

bool operator>(Cell const& x, Cell const& y) {
if(x.fValue > y.fValue) {
return true;
} else {
return false;
}
};


可是我发现这么干完以后根本没用,我跟踪了一下程序,发现PQ里的元素是胡乱排的,根本没按照fValue来排。甚至我注释掉这几行以后程序运行结果也没变。

请问大家怎样才能实现我的目的?

谢谢。
...全文
345 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
rollthewong 2012-02-09
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 jim_king_2000 的回复:]

PQ的定义如下:
template < class T, class Container = vector<T>,
class Compare = less<typename Container::value_type> > class priority_queue;
也就是说,第三个模板参数决定了按照神马来排序。默认的话,按照指针值来排序。你需要写一个predica……
[/Quote]

哥们,感激之情真是无以言表了!这个问题困扰我好几个小时了,从网上搜索来搜索去也没找到这么个简明实用的例子,而我这道非常重要的作业题又正好卡在这儿,眼看还有2个小时就deadline了,心里很着急。我发这贴其实真没想到能得到答案,而且还是在这么短时间内,你的回复真是让我高兴坏了。

这是我仅剩下的全部分数,我要是有更多的话肯定给你追加100分。

再次感谢!
Jim_King_2000 2012-02-09
  • 打赏
  • 举报
回复
bool operator()(const Cell *c1, const Cell *c2) const
Jim_King_2000 2012-02-09
  • 打赏
  • 举报
回复
PQ的定义如下:
template < class T, class Container = vector<T>,
class Compare = less<typename Container::value_type> > class priority_queue;
也就是说,第三个模板参数决定了按照神马来排序。默认的话,按照指针值来排序。你需要写一个predicate,按照pCell->fValue来排序。

class CellLess
{
public:
bool operator()(Cell *c1, Cell *c2) const
{
return c1->fValue < c2->fValue;
}
};

priority_queue<Cell*, vector<Cell*>, CellLess> openSet;
rollthewong 2012-02-09
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 jim_king_2000 的回复:]

你的PQ是如何定义的?
[/Quote]

priority_queue<Cell*> openSet;
Jim_King_2000 2012-02-09
  • 打赏
  • 举报
回复
你的PQ是如何定义的?

64,654

社区成员

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

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