0
#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();
}

我正在制作一棵二叉树。我的树中有指向左右子节点的指针,每个节点都有一个键和一个字符串值。在我的析构函数中,我正在从文件中读取并将键和值存储在节点中。文件的每一行都具有以下格式: "M. Ubiquity~ 14100148" - 值是名称后跟键。每当我运行此代码时,都会出现分段错误错误,但我似乎无法找到错误。任何提示/帮助将不胜感激。

4

2 回答 2

1

你有Root=NULL;,然后几行TreeNode<T> *temp = Root;,所以你有temp=NULL.

显然,while (temp!=NULL)从不执行和之后的while循环会temp->value=buffer;导致分段错误!

于 2013-02-23T13:15:42.647 回答
0

指针只能与内存地址相关联,而不能与值相关联。主要有两种方法:如果你有一个自动变量,你可以将它的地址分配给这样的指针:

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;

所以如果你在树中放置新元素,你必须为它们分配内存,如果你删除一个元素,你必须用delete来破坏。您必须注意不要破坏列表。

于 2013-02-23T14:13:52.657 回答