Search code examples
c++c++11priority-queuestd

invalid operands to binary expression when push element in a priority queue


I'm new in c++ programming. I've to create a priority queue of a Class named Container. So I've written this way:

In main.cpp:

struct Comp{
    bool operator() (const Container& a, const Container& b){
        return a<b;
    }
};

std::priority_queue<Container, std::list<Container>, Comp> containers;

In Container.cpp:

class Container{
public:
    friend bool operator< (const Container& a, const Container& b);
    //...
};

bool operator<(const Container &a, const Container &b) {
    return a.y<b.y;
}

I don't know why, even if I've declared a < operator overload, it gives me the same error:

error: invalid operands to binary expression ('std::__1::__list_iterator<Container, void *>' and 'std::__1::__list_iterator<Container, void *>')
    __sift_up<_Comp_ref>(__first, __last, __comp, __last - __first); 

How can I resolve this ? I don't really know what's going on :(


Solution

  • It's telling you that your it can't calculate the difference between two iterators of type list<Container>::interator.

    If you look at the requirements for priority_queue on CppReference it says that the iterators for the container "must satisfy the requirements of LegacyRandomAccessIterator."

    lists iterators are not random-access; they are bidirectional. Therefore, you can't use a list as the underlying container for a priority_queue.

    Simple fix: Use a deque instead of a list.

    std::priority_queue<Container, std::deque<Container>, Comp> containers;