简体   繁体   中英

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:(

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."

list s 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM