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

问题描述 投票:12回答:1

我的代码应该在一个文本文件中读取,并且有多个线程通过不同的行查看最长的回文。块的大小(多少行)由作为参数传入的可变数量的线程确定。原始文本文件存储在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;
}

任何帮助将不胜感激,这是我的第一个堆栈问题,对任何错误感到抱歉。

c++ string null
1个回答
12
投票

chunk向量不再存在于for循环体的末端。它仍然被一些线程引用。这被称为悬挂参考,它非常不合适。

但是,您看到的错误可能与Result有关。你没有提供它的定义(或者你在撰写这个答案时没有提供它),所以很难说。请记住,作为那个问代码有什么问题的人,可证明没有资格决定什么是重要的或者不显示:如果你知道,那么你可能知道什么是错的。

© www.soinside.com 2019 - 2024. All rights reserved.