我有一個關於Trie數據結構的具體問題,以及我的代碼出了什麼問題。當遞歸調用插入時,函數參數根始終爲NULL。這裏是我的代碼:插入Trie,NULL指針
代碼:
//subNodes is an array of TrieNode pointers that contains indices for all letters in the alphabet
bool insert(const string& word, TrieNode* root, int curI = 0)
//PRE: word must be a valid word in a dictionary
//POST: True when a word is inserted into the Trie, false otherwise
{
if(curI >= word.length()) //word has been scanned fully
{
root->isWord = true;
return true;
}
else //word has more letters to be scanned
{
if(root->subNodes[word[curI] - 'A'] == NULL) //if the current letter of the word is not in the trie
{ // insert the letter and advance the current letter of the word
root->subNodes[word[curI] - 'A'] = new TrieNode(word[curI]);
insert(word, root->subNodes[word[curI] - 'A'], curI++);
}
else //if the currrent letter of the word is in the trie
{ // advance the current letter of the word
insert(word, root->subNodes[word[curI] - 'A'], curI++);
}
}
}
我用subNodes[word[13]]
更換subNodes[word[curI] - 'A']
測試了這個(13
是字母表中N
索引和我在測試這個詞不是)和根無該調用更長的NULL。因此,索引出現問題。有誰知道什麼是錯的?我考慮過使用C++映射或向量。有人對使用數組有任何分歧嗎?
在C++中,不能保證傳遞給函數的參數的順序被評估。所以,你的編譯器可能會決定傳入舊的curI作爲最後一個參數,但是使用新的(遞增的)值作爲單詞的索引。 – 2012-01-04 01:27:02
不是它與你的問題有任何關係(其他人已經解決了你的問題),但我會重構你的兩個'insert'調用(它們是相同的),從他們的'if/else'塊中,只是一個'if(root-> subNodes [...] == NULL)root-> subNodes [...] = new TrieNode(word [curI]);''接着'insert(word,root-> subNodes [ ...],curI + 1);'(爲簡潔起見,添加了橢圓)。只是我的2c。 – Mac 2012-01-04 01:47:28