basic_string::_M_construct null 在构造字符串的子向量后无效

basic_string::_M_construct null not valid after constructing subvector of strings

本文关键字:字符串 无效 向量 string construct null basic      更新时间:2023-10-16

我的代码应该在一个文本文件中读取,并让多个线程在不同的行块中查看最长的回文。块的大小(多少行)由作为参数传入的可变数量的线程决定。原始文本文件存储在 std::vector 中,其中矢量的每个索引对应于原始文件。

当我将子向量块传递给 findPalindome() 时,我得到一个"C++ basic_string::_M_construct null 无效",我不知道为什么。我的字符串都不应该为 NULL。

当我传递原始向量线时,我没有收到任何错误,所以我假设这与我创建子向量的方式有关。

这是我的代码:

Result longestPalindrome(std::string str)
{
    int maxLength = 1;  // The result (length of LPS)
    int start = 0;
    int len = str.size();
    int low, high;
    // One by one consider every character as center point of 
    // even and length palindromes
    for (int i = 1; i < len; ++i)
    {
        // Find the longest even length palindrome with center points
        // as i-1 and i.  
        low = i - 1;
        high = i;
        while (low >= 0 && high < len && str[low] == str[high])
        {
            if (high - low + 1 > maxLength)
            {
                start = low;
                maxLength = high - low + 1;
            }
            --low;
            ++high;
        }
        // Find the longest odd length palindrome with center 
        // point as i
        low = i - 1;
        high = i + 1;
        while (low >= 0 && high < len && str[low] == str[high])
        {
             if (high - low + 1 > maxLength)
             {
                start = low;
                maxLength = high - low + 1;
             }
             --low;
            ++high;
        }
    }
    Result result = {0, 0, 0};
    return result;
}
void findPalindome(std::vector<std::string> chunk, Result& result)
{
    Result localLargest = {0,0,0};
    for (unsigned int i = 0; i < chunk.size(); i++)
    {
        Result loopLargest = longestPalindrome(chunk[i]);
        if (localLargest < loopLargest)
        {
            localLargest = loopLargest;
        }
    }
    result = localLargest;
}
Result
FindPalindromeStatic(Lines const& lines, int numThreads)
{
    std::vector<Result> results(numThreads, {0,0,0});;
    int chunkSize = lines.size() / numThreads; //lines is the original vector with all the lines in the file
    std::vector<std::thread> threads;
    int counter = 0;
    for (int i = 0; i < numThreads; i++)
    {
        std::vector<std::string>::const_iterator begin = lines.begin() + counter;
        std::vector<std::string>::const_iterator end = lines.begin() + ((i + 1) * chunkSize);
        std::vector<std::string> chunk(begin, end);
        threads.emplace_back(&findPalindome, std::ref(chunk), std::ref(results[i]));
        counter = ((i+1)*chunkSize);
    }
    for (int i = 0; i < numThreads; i++)
    {
        threads[i].join();
    }
    Result x = {0,0,0};
    return x;
}
任何

帮助将不胜感激,这是我的第一个堆栈问题,因此对任何错误表示歉意。

chunk向量在for循环体的末尾不再存在。它仍然被某个线程引用。这叫悬而未决的引用,不好。

但是,您看到的错误可能与Result有关。它的定义没有提供(在撰写此答案时),因此很难说。请记住,作为询问代码出了什么问题的人,可能没有资格决定什么是重要的或不显示的。