C++ C++;Trie搜索性能
所以我做了一个trie,它保存了大量的数据,我的搜索算法非常快,但我想看看是否有人对我如何使它更快有任何见解C++ C++;Trie搜索性能,c++,performance,search,trie,C++,Performance,Search,Trie,所以我做了一个trie,它保存了大量的数据,我的搜索算法非常快,但我想看看是否有人对我如何使它更快有任何见解 bool search (string word) { int wordLength = word.length(); node *current = head; for (unsigned int i=0; i<wordLength; ++i) { if (current->child[((int)word[i
bool search (string word)
{
int wordLength = word.length();
node *current = head;
for (unsigned int i=0; i<wordLength; ++i)
{
if (current->child[((int)word[i]+(int)'a')] == NULL)
return false;
else
current = current->child[((int)word[i]+(int)'a')];
}
return current->is_end;
}
bool搜索(字符串字)
{
int wordLength=word.length();
节点*电流=头部;
for(无符号整数i=0;ichild[(整数)字[i]+(整数)'a')]==NULL)
返回false;
其他的
当前=当前->子项[((int)字[i]+(int)'a');
}
返回当前->正在结束;
}
调用此函数时,将复制字符串word
,
下面的函数类型将更快
bool search (const string &word)
或
就性能而言,除了以下花絮外,它看起来很好:
- 将函数参数声明为
(而不仅仅是常量字符串&
),以避免不必要的复制字符串
- 您可以在
前面提取公共子表达式if
,以避免重复并使代码稍微更小,但任何值得使用的编译器都会为您进行优化current->child[(int)word[i]+(int)“a')]
“风格”建议:
- 如果
包含“a”下面的字符(如大写字母、数字、标点符号、新行等),该怎么办?您需要验证输入,以避免访问错误的内存位置和崩溃。这不应该是word
而不是-(int)'a'
(我假设您只想支持有限的字符集:'a'及以上)+
- 将
声明为wordLength
(或者更好的是size\u t
),但这对于任何实际长度的字符串都不重要(如果auto
大于size\u t
,甚至可能会稍微影响性能)。int
同上i
word[i]
中添加任何内容。确定有效范围,并(可选)通过从word[i]
中减去范围中的最低值,将范围从0开始移动。
bool search (const string &word)
bool search (const char *word)