[英]invalid operands to binary expression when push element in a priority queue
I'm new in c++ programming.我是 c++ 编程的新手。 I've to create a priority queue of a Class named Container.
我必须创建一个名为 Container 的 Class 的优先级队列。 So I've written this way:
所以我这样写:
In main.cpp:在 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:在 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
.它告诉您它无法计算
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."如果您查看CppReference上对
priority_queue
的要求,它会说容器的迭代器“必须满足 LegacyRandomAccessIterator 的要求”。
list
s iterators are not random-access; list
的迭代器不是随机访问的; they are bidirectional.它们是双向的。 Therefore, you can't use a
list
as the underlying container for a priority_queue
.因此,您不能将
list
用作priority_queue
的底层容器。
Simple fix: Use a deque
instead of a list
.简单修复:使用
deque
而不是list
。
std::priority_queue<Container, std::deque<Container>, Comp> containers;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.