我正在执行此程序,该程序读取CSV文件并将其输入到树中,直到现在我设法创建了树并按顺序显示了它们,但是通过搜索,我失败了,因为它没有显示信息关于正在搜索的元素,可以帮助我纠正错误的人,谢谢....
csv文件包含数据(包含多个数据,但我以这些为例。):
1,name1,number12,名称2,编号23,name3,number3
#include <iostream>
#include <iomanip>
#include <fstream>
#include <memory>
#include <string>
#include <sstream>
#include <vector>
#include <utility>
#include <experimental/optional>
intmax_t dato;
struct Person {
intmax_t key;
std::string name;
intmax_t num;
};
struct Node : Person {
Node(const Person &person) : Person(person) {}
std::unique_ptr<Node> left, right;
void insert(const Person &person);
};
void Node::insert(const Person &person) {
/* recur down the tree */
if (key > person.key) {
if (left)
left->insert(person);
else
left = std::make_unique<Node>(person);
} else if (key < person.key) {
if (right)
right->insert(person);
else
right = std::make_unique<Node>(person);
}
}
std::vector<Person> persons;
void inorder(Node *root) {
if (root) {
// cout<<"\t";
inorder(root->left.get());
std::cout << "\tID: "<< root->key << "\tName: "<< root->name << "\t\tNum: " << root->num << '\n'; //'\t' ' '
inorder(root->right.get());
}
}
std::experimental::optional<Person> busqueda(Node *root, intmax_t dato) {
if(root==NULL){
return {};
}
else if(root->key==dato){
return *root;
}
else if(dato<root->key){
return busqueda(root->left.get(),dato);
}
else{
return busqueda(root->right.get(),dato);
}
}
int main() {
std::unique_ptr<Node> root;
std::ifstream fin("data.txt");
if (!fin) {
std::cout << "File not open\n";
return 1;
}
std::string line;
const char delim = ',';
std::cout<<"\t\tData\n"<<std::endl;
while (std::getline(fin, line)) {
std::istringstream ss(line);
Person person;
ss >> person.key;
ss.ignore(10, delim);
std::getline(ss, person.name, delim);
ss >> person.num;
if (ss) persons.push_back(person);
}
for (unsigned int i = 0; i < persons.size(); i++) {
std::cout << std::setw(10)<<"ID: " << persons[i].key << std::setw(30)<<"Name: "
<< persons[i].name << std::setw(20) <<"Num: "<< persons[i].num << '\n';
if (!root) root = std::make_unique<Node>(persons[i]);
else root->insert(persons[i]);
}
std::cout << "\n\n\t\tInorder:\n\n";
inorder(root.get());
std::cout<<" Enter data: "; std::cin>> dato;
busqueda(root.get(),dato);
if(busqueda(root.get(),dato)){
std::cout<<"Data found"<<std::endl;
std::cout<<root->name;//does not show the wanted, only the first of the document.
}
else{
std::cout<<"\nData not found"<<std::endl;
}
return 0;
}
从注释中,您在下面的语句中放弃了搜索结果: