[英]What is happening in the following code of a trie
我正在查看这个Trie的示例 ,但是我很难理解以下代码
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
在az之间,则index
的结果将始终为>= 0
。
否则currentChar
不在az之间,因为index
将是负数,由于tolower()
函数,currentChar不能在AZ
之间。
您可以转至此链接以了解有关ASCII
值的更多信息
另外,您还需要更新条件assert(index >= 0 && index < 26)
因为{,},| 和〜将使索引> = 0
它会给您字母中的字母位置,将a
视为位置0
。 这里a
被转换成其ASCII代码,并将其从subsctracted az
字母变得更容易处理。
人们容易忘记的是-字符是其中包含ascii值的字节。
所以在ascii表中“ a”是97(我认为),所以所有工作都已完成-是currentChar-97。
请按照http://www.asciitable.com了解实际值。
但请始终记住-字符是一个字节,您可以多次使用此事实!
我正在用它跳过指针中的内存地址(例如:
void* a = (void*)((char*)arr+2);
这段代码将返回arr +两个字节的内存,而忽略了arr中持有的类型)
请注意-|'a'-'A'| = |'A'-'a'|| ,但一个将为负,而另一个将为正
int索引= currentChar-'a'; 这是为了检查字符,因为用户可以输入a到z之间的字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.