0

我正在尝试编写一个程序,该程序使用两种不同的字符串搜索算法搜索电影脚本。但是警告C26451:在 4 字节值上使用运算符“+”然后将结果转换为 8 字节值的算术溢出继续出现在 rabin karp 的计算哈希部分中,是否有解决此问题的方法?任何帮助将不胜感激。

#define d 256
Position rabinkarp(const string& pat, const string& text) {

    int M = pat.size();
    int N = text.size();
    int i, j;
    int p = 0; // hash value for pattern  
    int t = 0; // hash value for txt  
    int h = 1;
int q = 101;
    // The value of h would be "pow(d, M-1)%q"  
    for (i = 0; i < M - 1; i++)
        h = (h * d) % q;

    // Calculate the hash value of pattern and first  
    // window of text  
    for (i = 0; i < M; i++)
    {
        p = (d * p + pat[i]) % q;
        t = (d * t + text[i]) % q;
    }

    // Slide the pattern over text one by one  
    for (i = 0; i <= N - M; i++)
    {

        // Check the hash values of current window of text  
        // and pattern. If the hash values match then only  
        // check for characters on by one  
        if (p == t)
        {
            /* Check for characters one by one */
            for (j = 0; j < M; j++)
            {
                if (text[i + j] != pat[j])
                    break;
            }

            // if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1]  
            if (j == M)

            return i;
        }

        // Calculate hash value for next window of text: Remove  
        // leading digit, add trailing digit  
        if (i < N - M)
        {
            t = (d * (t - text[i] * h) + text[i + M]) % q;//   <---- warning is here 

[i + M


            // We might get negative value of t, converting it  
            // to positive  
            if (t < 0)
                t = (t + q);
        }
    }

    return -1;
}

错误的上下文

4

1 回答 1

1

您要添加两个int,在您的情况下是 4 个字节,而在您的情况下std::string::size_type可能是 8 个字节。当您执行以下操作时,会发生所述转换:

 text[i + M]

这是对作为参数的std::string::operator[]调用std::string::size_type

使用std::string::size_type,通常与 相同size_t

gcc 没有给出任何警告,即使有-Wall -Wextra -pedantic,所以我猜你真的激活了每一个警告,或者类似的东西

于 2020-03-06T17:57:08.907 回答