我正在浏览Trie的example,但难以理解以下代码

void Trie::addWord(string word)
{
    Node * currentNode = root;

    for (int i = 0; i < word.size(); ++i)
    {
        char currentChar = tolower(word.at(i));
        int index = currentChar - 'a';
        assert(index >= 0);     // Makes sure the character is between a-z
        if (currentNode->children[index] != NULL)
        {
            // check if the current node has the current character as one of its decendants
            currentNode = currentNode->children[index];
        }
        else
        {
            // the current node doesn't have the current character as one of its decendants
            Node * newNode = new Node(currentChar);
            currentNode->children[index] = newNode;
            currentNode = newNode;
        }
        if (i == word.size() - 1)
        {
            // the last character of the word has been reached
            currentNode->end = true;
        }
    }
}

我的问题是为什么在这里减去a
 int index = currentChar - 'a';

最佳答案

int index = currentChar - 'a';行处currentChar(无论它是什么)都将被具有ASCII值97的'a'字符减去。
在这种情况下,您有两个条件:

  • 首先如果currentChar在a-z之间,则index的结果将始终为>= 0
  • 否则currentChar不在a-z之间,因为index将为负数,由于A-Z函数,currentChar不能在tolower()之间。

  • 您可以引用此link,以进一步了解ASCII

    另外,您还需要更新条件assert(index >= 0 && index < 26),因为{,},|和〜将使索引> = 0

    关于c++ - 下面的trie代码中发生了什么,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22799711/

    10-12 00:22