【发布时间】:2021-12-17 15:35:02
【问题描述】:
我是 C++ 的初学者,我在下面看到了这个用于向 trie 添加单词的函数,并且对我用问号评论的那一行感到困惑。作者是否在这里将 char 值分配给 int ?将分配什么 int 值?
struct TrieNode
{
struct TrieNode *children[ALPHABET_SIZE];
// isEndOfWord is true if the node represents
// end of a word
bool isEndOfWord;
};
void insert(struct TrieNode *root, string key)
{
struct TrieNode *pCrawl = root;
for (int i = 0; i < key.length(); i++)
{
int index = key[i] - 'a'; // ?
if (!pCrawl->children[index])
pCrawl->children[index] = getNode();
pCrawl = pCrawl->children[index];
}
// mark last node as leaf
pCrawl->isEndOfWord = true;
}
【问题讨论】:
-
字符是小整数。
'a' - 'a'为 0,'b' - 'a'为 1,以此类推 -
没有。
char实际上是一个数字。a根据 ASCII 等于 97。这是将字符指向的索引对齐为 0 的某种“技巧”。 -
这是一段糟糕的 C++ 代码。不要从向初学者提供此类示例的资源中学习,更喜欢由真正的专业人士编写的books。
-
注释说明明显而未提及不明显说明作者错过了 cmets 的重点(或不太了解自己的代码)。
TrieNode代表一个 trie 节点,如果该节点是单词的结尾,bool isEndOfWord是否为真?真的吗?我永远猜不到。另一方面,插入循环背后的逻辑对任何人来说都是显而易见的......