使用tire树,来统计文本中每个单词的出现次数。程序出现错误,请大牛帮忙
程序功能:使用tire树,来统计文本中每个单词的出现次数
但是,在调用类的析构函数时,出现错误Windows 已在 程序测试.exe 中触发
自己找了好久,能确定是 析构函数delete[] pRoot->word; //此处报错,
但是,不觉得这句话有错误,请高手改下
#include <iostream>#include <fstream>#include <string>#include <algorithm>#include <assert.h>using namespace std;const int MaxBranchNum = 26;/*定义trie树结点*/class TrieNode{public: char* word; int count; TrieNode* nextBranch[MaxBranchNum];public: TrieNode() : word(NULL),count(0) { memset(nextBranch,NULL,sizeof(TrieNode*) * MaxBranchNum); }};/*定义类Trie*/class Trie{public: Trie(); ~Trie(); void Insert(const char* str); void Print();private: TrieNode* pRoot;private: void Destory(TrieNode* pRoot); void Print(TrieNode* pRoot);};Trie::Trie(){ pRoot = new TrieNode();}Trie::~Trie(){ Destory(pRoot);}void Trie::Insert(const char* str){ assert(NULL != str); int index; TrieNode* pLoc = pRoot; for (int i = 0;str[i];i++) { index = str[i] - 'a';//如果区分大小写,可以扩展 if(index < 0 && index > MaxBranchNum)//不执行插入 { return; } if (NULL == pLoc->nextBranch[index]) { pLoc->nextBranch[index] = new TrieNode(); } pLoc = pLoc->nextBranch[index]; } if (NULL != pLoc->word)//单词已经出现过 { pLoc->count++; return; } else //单词没有出现过,应该插入单词 { pLoc->count++; pLoc->word = new char[strlen(str) + 1]; assert(NULL != pLoc->word); strcpy_s(pLoc->word,strlen(pLoc->word),str); }}void Trie::Print(){ Print(pRoot);}/*输出所有的单词*/void Trie::Print(TrieNode* pRoot){ if (NULL == pRoot) { return; } //输出单词 if (NULL != pRoot->word) { cout<<pRoot->word<<" "<<pRoot->count<<endl; } //递归处理分支 for (int i = 0;i < MaxBranchNum;i++) { Print(pRoot->nextBranch[i]); }}/*销毁trie树*/void Trie::Destory(TrieNode* pRoot){ if (NULL == pRoot) { return; } for (int i = 0;i < MaxBranchNum;i++) { Destory(pRoot->nextBranch[i]); } //销毁单词占得空间 if (NULL != pRoot->word) { delete []pRoot->word; //此处报错 pRoot->word = NULL; } delete pRoot;//销毁结点 pRoot = NULL;}int main(){ Trie t; string str = "abc"; t.Insert(str.c_str()); t.Print();}