使用模板时出现错误C2678

error C2678 in using template

本文关键字:错误 C2678      更新时间:2023-10-16

我正在定义一个优先级队列,并在自定义结构上使用它,但我遇到了这个错误,我不知道如何修复它。

这是我的错误:

error C2678: binary '<' : no operator found which takes a left-hand operand 
of type 'const Location' (or there is no acceptable conversion)

我的结构位置

struct Location
{
   int x, y, value;
   Location(int a, int b);
   bool operator == (const Location& other);
   bool operator < (const Location& other);
};
Location:: Location(int a, int b) {
   x = a;
   y = b;
   value = 0;
}
bool Location:: operator == (const Location& other) {
    return (x == other.x && y == other.y);
}
bool Location:: operator < (const Location& other) {
    return value > other.value;
}

这是我的优先队列

template<typename T>
struct my_priority_queue {
priority_queue<T, vector<T>, greater<T>> elements;
bool empty()
{
    return elements.empty();
}
void push(T item)
{
    elements.emplace(item);
}
T pop() 
{
    T best = elements.top();
    elements.pop();
    return best;
}
};

的主要功能

int main() {
    Location a(0, 0);
    Location b(1, 2);
    Location c(3, 0);
    my_priority_queue<Location> my_pq;
    my_pq.push(a);
}

正如它所说。

操作员不能在LHS上获取const Location,因为它不是const函数。

bool operator == (const Location& other) const;
bool operator <  (const Location& other) const;
//                                      ^^^^^^
相关文章: