gpt4 book ai didi

c++ - 遇到段错误 : It looks like my comparator is trying to compare nodes out of scope

转载 作者:行者123 更新时间:2023-11-28 03:21:38 25 4
gpt4 key购买 nike

我遇到了段错误。我相信这与我进行比较的方式有关。我对 C++ 感到难过和陌生。

最后一行 pq.pop() 是进入堆栈跟踪并导致失败的调用。执行 ./a.out 时没有打印出任何东西

class Node {
public:

Node() {}

Node(int b) {
bound = b;
}

Node(int b, Node * p) {
bound = b;
parent = p;
}

void addChild(Node& n) {
n.parent = this;
}

Node * parent;

int bound;
};



class CompareNode {

public:
bool operator()(Node *n, Node *o)
{
cout << "Comparing " << n->bound;
cout << " to " << o-> bound <<endl;
return n->bound > o->bound;
}
};


在主目录下


std::priority_queue<Node*, vector<Node*>, CompareNode> pq;
Node* root = new Node();
Node* node;
for(int i = 0; i < n; i++) {
node = new Node(matrix[0][i], root);
pq.push(node);
}

pq.pop();


GDB


(gdb) run
Program received signal SIGSEGV, Segmentation fault.
0x00000000004027e7 in void std::__pop_heap<__gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, CompareNode>(__gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, __gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, __gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, CompareNode) ()
(gdb) backtrace
#0 0x00000000004027e7 in void std::__pop_heap<__gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, CompareNode>(__gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, __gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, __gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, CompareNode) ()
#1 0x0000000000401e13 in void std::pop_heap<__gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, CompareNode>(__gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, __gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, CompareNode)
()
#2 0x0000000000401a11 in std::priority_queue<Node*, std::vector<Node*, std::allocator<Node*> >, CompareNode>::pop() ()
#3 0x00000000004015dc in main ()

最佳答案

C++ 并不经常为您检查必要的先决条件。如果在空结构上调用 pop,结果很可能是崩溃。所以这是我首先要看的地方。

您可以使用 -D_GLIBCXX_DEBUG 在 GCC 中获取此检查。它添加了边界检查、迭代器验证等,在任何情况下都是一套很好的训练轮。

关于c++ - 遇到段错误 : It looks like my comparator is trying to compare nodes out of scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15263017/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com