作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以我遇到的问题是段错误。我正在尝试实现一个 AVLtree,我相信我的这部分代码是问题所在,但我无法确定我做错了什么。
我的 AVLtree 类的一部分:
Node* AVLtree::findNode(string cityID){
Node *thisNode = this->rootNode;
while(thisNode!=0){
if(thisNode->getCity()->getName().compare(cityID)==0){return thisNode;
}else if(thisNode->getChildR()->getCity()->getName() < cityID){ thisNode = thisNode->getChildR();
}else{thisNode = thisNode->getChildL();}
}
return this->rootNode;
}
我的主文件:
int main(){
....
City city1("BoomTown", "EU", 1.01, 2.02);
....
AVLtree avltree1(&city1);
cout<< "TEST 1: AVLtree with city paramter of city1 (" << city1.getName()<< ")" << endl;
cout << "TEST 2: Getting name of city1: " << avltree1.findNode("BoomTown")->getCity()->getName() << endl;
我的 City 类和 Node 类都可以工作,我可以创建一个 AVLtree。我似乎无法在其中找到节点。
这是我的输出:
$ ./mainTest
TEST 1: AVLtree with city paramter of city1 (BoomTown)
Segmentation fault (core dumped)
如果这是一个简单的错误,我很抱歉,但我是 C++ 的新手,需要时间和练习来学习:)提前致谢。
(附注:如果您需要更多代码,请询问)
最佳答案
在您的代码中,您似乎检查了当前节点是否为空,但在访问它之前没有检查子节点是否为空:
while(thisNode!=0) {
// ...
if(thisNode->getChildR()->getCity()->getName() < cityID){
^^^^^^^^^^^
here
关于C++ 段错误(核心已转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20025242/
我是一名优秀的程序员,十分优秀!