Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/156.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;Trie搜索性能_C++_Performance_Search_Trie - Fatal编程技术网

C++ C++;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

所以我做了一个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]+(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')]
    ,以避免重复并使代码稍微更小,但任何值得使用的编译器都会为您进行优化

“风格”建议:

  • 如果
    word
    包含“a”下面的字符(如大写字母、数字、标点符号、新行等),该怎么办?您需要验证输入,以避免访问错误的内存位置和崩溃。这不应该是
    -(int)'a'
    而不是
    +
    (我假设您只想支持有限的字符集:'a'及以上)
  • wordLength
    声明为
    size\u t
    (或者更好的是
    auto
    ),但这对于任何实际长度的字符串都不重要(如果
    size\u t
    大于
    int
    ,甚至可能会稍微影响性能)。
    i
    同上

我使用+(int)a,因为下面有带值的字符a@that_guy:在这种情况下,您不应该在
word[i]
中添加任何内容。确定有效范围,并(可选)通过从
word[i]
中减去范围中的最低值,将范围从0开始移动。
bool search (const string &word)
bool search (const char *word)