【问题标题】:Assigning a char value to an int将 char 值分配给 int
【发布时间】: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 是否为真?真的吗?我永远猜不到。另一方面,插入循环背后的逻辑对任何人来说都是显而易见的......

标签: c++ types


【解决方案1】:

char 只是一个 1 字节的数字。计算机使用您计算机使用的任何字符编码(主要是ASCII)将这些数字编码为一个字符。

ASCII 中,a 的值为97b 的值为98,...,z 的值为122

所以:

If key[i] is "a", value = 97 - 97 = 0
If key[i] is "b", value = 98 - 97 = 1
If key[i] is "c", value = 99 - 97 = 2
...
If key[i] is "z", value = 122 - 97 = 25

因此,您可以看到,这是将key[i] 的所有值从0 映射到25 的“技巧”

【讨论】:

    猜你喜欢
    • 2023-03-26
    • 2023-02-22
    • 2012-12-10
    • 2018-02-03
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多