为了理解priority_queue,我编写了以下C ++程序。
#include <queue>
struct Node {
bool operator<(const Node& r) {
return a < r.a;
}
int a;
};
int main(int argc, char *argv[])
{
std::priority_queue<Node, std::vector<Node>> heap;
return 0;
}
我正在使用以下命令编译它。
g++ -c testMinHeap.cpp -std=c++1y
但是它导致了以下错误。
g++ -c testMinHeap.cpp -g -std=c++1y
In file included from /usr/include/c++/5/queue:63:0,
from testMinHeap.cpp:1:
/usr/include/c++/5/bits/stl_function.h: In instantiation of ‘constexpr bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = Node]’:
/usr/include/c++/5/bits/predefined_ops.h:123:46: required from ‘constexpr bool __gnu_cxx::__ops::_Iter_comp_iter<_Compare>::operator()(_Iterator1, _Iterator\
2) [with _Iterator1 = __gnu_cxx::__normal_iterator<Node*, std::vector<Node> >; _Iterator2 = __gnu_cxx::__normal_iterator<Node*, std::vector<Node> >; _Compare \
= std::less<Node>]’
/usr/include/c++/5/bits/stl_heap.h:215:14: required from ‘void std::__adjust_heap(_RandomAccessIterator, _Distance, _Distance, _Tp, _Compare) [with _RandomA\
ccessIterator = __gnu_cxx::__normal_iterator<Node*, std::vector<Node> >; _Distance = long int; _Tp = Node; _Compare = __gnu_cxx::__ops::_Iter_comp_iter<std::l\
ess<Node> >]’
/usr/include/c++/5/bits/stl_heap.h:333:22: required from ‘void std::__make_heap(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessI\
terator = __gnu_cxx::__normal_iterator<Node*, std::vector<Node> >; _Compare = __gnu_cxx::__ops::_Iter_comp_iter<std::less<Node> >]’
/usr/include/c++/5/bits/stl_heap.h:384:23: required from ‘void std::make_heap(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIte\
rator = __gnu_cxx::__normal_iterator<Node*, std::vector<Node> >; _Compare = std::less<Node>]’
/usr/include/c++/5/bits/stl_queue.h:414:23: required from ‘std::priority_queue<_Tp, _Sequence, _Compare>::priority_queue(const _Compare&, _Sequence&&) [with\
_Tp = Node; _Sequence = std::vector<Node>; _Compare = std::less<Node>]’
testMinHeap.cpp:13:47: required from here
/usr/include/c++/5/bits/stl_function.h:387:20: error: no match for ‘operator<’ (operand types are ‘const Node’ and ‘const Node’)
{ return __x < __y; }
^
testMinHeap.cpp:4:7: note: candidate: bool Node::operator<(const Node&) <near match>
bool operator<(const Node& r) {
^
没有得到&#39;&lt;&#39;(小于)运算符的定义。 在priority_queue变量声明期间,我没有给出 Comp 模板参数,假设它将使用 less&lt; T&gt; 是默认值。 对于类型T(即节点),我已经重载了运算符&lt; 。 如果我在这里做错了,请指出我。
感谢。