我编写了这个BST来计算给定文件中每个单词的数量。该文件每行都有重复的单词。
/*all necessary headers*/
class tree
{
public:
tree(string _word) : left( NULL ), right ( NULL ), m_word(_word), count(1) {}
tree* createTree(tree *newNode, string _word)
{
if( newNode == NULL )
newNode = new tree(_word);
else if( _word == newNode->m_word)
newNode->count++;
else if( _word < m_word)
newNode->left = createTree(newNode->left,_word);
else
newNode->right = createTree(newNode->right,_word);
return newNode;
}
private:
string m_word;
int count;
tree *left;
tree *right;
};
int main()
{
string csword;
tree *node = NULL;
ifstream str("word.txt");
while( !str.eof())
{
str>>csword;
node = node->createTree(node,csword);
}
}
我的查询是:1.在main()
中,我将node
初始化为NULL
,并且我使用相同的指针来调用trees
方法。程序不应该崩溃吗?既然我正在取消引用NULL
指针?
2:当我在g++编译器(gcc 4.6.3)上运行这段代码时,程序在_word == newNode->m_word
时交给createTree()
方法,不会返回。在else if ( _word == newNode->m_word )
条件下似乎存在一个无限循环。
但在VisualStudio2008上执行相同的代码并没有问题,我能够得到正确的答案
你知道查询1和2吗?
根据实现(我的是MSVC++),只有当您实际访问不存在对象的任何成员时,它才可能导致分段错误。由于createTree
不接触任何东西,它的工作方式几乎像一个静态函数,不会导致分割故障。
也许你应该让它成为static
,比现在的方式更有意义。