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

时间:2016-02-02 01:01:19

标签: c++ string null

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

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

1 个答案:

答案 0 :(得分:12)

chunk向量不再存在于for循环体的末尾。它仍然被一些线程引用。这被称为悬空参考,而且非常不合时宜。

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