C++ 二叉树(从文件读取) #包括 #包括 #包括 使用名称空间std; 模板 树状结构{ 字符串值; T键; TreeNode*LeftChild; TreeNode*右儿童; 树节点(Tk,字符串值) { 该->值=Val; 该->键=k; 此->LeftChild=NULL; 此->RightChild=NULL; } }; 模板 类二叉树{ 私人: 树根; 公众: 二叉树(); void insertNode(); }; 模板 BinaryTree::BinaryTree() { Root=NULL; 流鳍; fin.open(“names.txt”); 字符串缓冲区; T浅黄色; 而(!fin.eof()) { getline(fin,buffer,“~”); 鳍>>浅黄色; cout
您有C++ 二叉树(从文件读取) #包括 #包括 #包括 使用名称空间std; 模板 树状结构{ 字符串值; T键; TreeNode*LeftChild; TreeNode*右儿童; 树节点(Tk,字符串值) { 该->值=Val; 该->键=k; 此->LeftChild=NULL; 此->RightChild=NULL; } }; 模板 类二叉树{ 私人: 树根; 公众: 二叉树(); void insertNode(); }; 模板 BinaryTree::BinaryTree() { Root=NULL; 流鳍; fin.open(“names.txt”); 字符串缓冲区; T浅黄色; 而(!fin.eof()) { getline(fin,buffer,“~”); 鳍>>浅黄色; cout,c++,C++,您有Root=NULL;然后几行TreeNode*temp=Root;所以您有temp=NULL 显然,while(temp!=NULL)从不执行,在while循环之后,您有temp->value=buffer;,这会导致分段错误!指针只能与内存地址关联,而不能与值关联。主要有两种方法:如果您有一个自动变量,您可以将其地址分配给如下指针: #include <iostream> #include <string> #include <fstream> usin
Root=NULL;
然后几行TreeNode*temp=Root;
所以您有temp=NULL
显然,
while(temp!=NULL)
从不执行,在while循环之后,您有temp->value=buffer;
,这会导致分段错误!指针只能与内存地址关联,而不能与值关联。主要有两种方法:如果您有一个自动变量,您可以将其地址分配给如下指针:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
template <class T>
struct TreeNode{
string value;
T key;
TreeNode<T> *LeftChild;
TreeNode<T> *RightChild;
TreeNode (T k,string Val)
{
this->value=Val;
this->key=k;
this->LeftChild=NULL;
this->RightChild=NULL;
}
};
template <class T>
class BinaryTree{
private:
TreeNode<T> *Root;
public:
BinaryTree();
void insertNode();
};
template <class T>
BinaryTree<T>::BinaryTree()
{
Root=NULL;
ifstream fin;
fin.open("names.txt");
string buffer;
T buff;
while (!fin.eof())
{
getline(fin,buffer,'~');
fin>>buff;
cout<<buff<<buffer<<endl;
cout<<"down the tree"<<endl;
TreeNode<T> *temp=Root;
while (temp!=NULL)
{
TreeNode<T> *Right=temp->RightChild;
TreeNode<T> *Left=temp->LeftChild;
if (temp->key>buff)
{
temp=temp->LeftChild;
}
else if (temp->key<buff)
temp=temp->RightChild;
}
cout<<"further down"<<endl;
}
temp->value=buffer;
temp->key=buff;
cout<<"and done!"<<endl;
cout<<"hey"<<endl;
}
fin.close();
}
因此,如果在树中放置新元素,则必须为它们分配内存,如果删除元素,则必须使用delete进行销毁。您必须注意不要破坏列表。尝试通过gdb()之类的调试器运行程序它可以帮助你准确地发现分段错误发生的原因。为什么不打断SeGebug的发生?在代码中的任何地方都不分配任何内存,难怪你会出现分段错误……我会在开始用模板编写程序之前尝试C++基础知识。
int i = 6; //automatic variable
int *pi = &i;
std::cout << pi; // you get the address of pi (hexadecimal number)
std::cout << *pi; // 6
int *pi = new int(6);
delete pi;