开发者

Overloading operator< for priority queue

I am trying to make a priority queue of a class I made like this -

std::priority_queue<Position> nodes;

I overloaded the < operator in Position like this -

bool Position::operator<(Position& right) {
    return (fvalue < right.getFValue());
}

However, whenever I try to compile I get this error message saying the < operator is not overloaded -开发者_Python百科

error: no match for ‘operator<’ in ‘__x < __y’
position.h:30: note: candidates are: bool Position::operator<(Position&)

What am I missing here? Any help is appreciated.


Relational operators shouldn't change the operands. Try:

bool Position::operator<(const Position& right) const {

My guess is that either __x or __y (or both) are const. You can't call a non-const member function on __x if it's const, also you can't pass __y as the right parameter if __y is const and right is not.


  1. It's preferable not to overload the comparison operators just to satisfy a collection. (http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Operator_Overloading). It's better to use comparator objects or functions, if possible. If your operator defines how these objects are intrinsically ordered, rather than just what their priority should be in the queue, then it's OK. But if not, you could get into trouble if another developer uses your operator in another context.

  2. I'm not sure what fvalue is, but it's possible that it may not have operator < defined for it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜