jor*_*dpw 0 c++ search boolean binary-search-tree
除了"搜索"函数之外,此程序中的所有内容都有效,该函数根据字是否在二叉搜索树中返回true或false.我在"main"中有一个if语句,告诉用户该单词是否在树中.当我单步执行调试器时,它表示该函数应该返回true,但它会直接跳到"main"中if语句的else部分.为什么是这样?它似乎工作得很好,除非它被if语句"查看".例如,"test.txt"包含单词"This Program Works",每个单词在一行中.我知道它正在将它们添加到树中,因为当我"printAll"这些词出来时......
BinarySearchTree
#include "BinarySearchTree.h"
#include <iostream>
using namespace std;
bool BinarySearchTree::search(string target) {
if(target == data) {
return true;
}
else if(target < data) {
if(left == nullptr) {
return false;
}
else {
left->search(target);
}
}
else if(target > data) {
if(right == nullptr) {
return false;
}
else {
right->search(target);
}
}
}
Run Code Online (Sandbox Code Playgroud)
主要
#include <fstream>
#include <string>
#include <iostream>
#include <vector>
#include "BinarySearchTree.h"
using namespace std;
int main(int argc, char** argv) {
//pull in text from a .txt file, one word at a time, add each to the BinarySearchTree.
//loop and let the user enter a word, let the user know if the word was in the file or not. Have the user type 0 to quit.
cout<<"Search: ";
string target;
getline(cin,target);
while(target != "0") {
///////////////////MAIN ISSUE HERE/////////////////////////////////
if(tree.search(target) == true) {
cout<<"\""<<target<<"\""<<" found in file."<<endl;
}
else {
cout<<"\""<<target<<"\""<<" not found in file."<<endl;
}
////////////////////////////////////////////////////////////////////
cout<<"Search: ";
getline(cin,target);
}
//now that the user is content, print all words that were in the text file, in lexicographical order.
tree.printAll();
cout<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我知道其他一切都运作良好.
你在这里没有回复任何东西:
else {
left->search(target);
}
Run Code Online (Sandbox Code Playgroud)
它应该是:
else {
return left->search(target);
}
Run Code Online (Sandbox Code Playgroud)
你有同样的错误right->search(target).
| 归档时间: |
|
| 查看次数: |
1190 次 |
| 最近记录: |