计数排序无限循环

时间:2012-06-18 01:08:55

标签: c++ sorting for-loop

我正在编写计数排序功能,当我运行它时会弹出一个窗口,说“filename.exe已停止工作”。经过调试后,它似乎陷入了第二个for循环。让我感到困惑的是,如果我将maxInt设置为任何大于130000的数字,那么它可以工作,但如果它的130000或低于我得到的错误信息。我用来排序的文件只有大约20个数字。

#include <iterator>
#include <algorithm>
#include <vector>
#include <fstream>
#include <iostream>
using namespace std;

std::string file = "";
std::vector<int> numbers;

void CountingSort(vector<int> &numbers);

int main()
{
    std::cout << "Which file would you like to sort?\n";
    std::cin >> file;

    std::ifstream in(file.c_str());

    // Read all the ints from in:
    std::copy(std::istream_iterator<int>(in), std::istream_iterator<int>(),
            std::back_inserter(numbers));

    CountingSort(numbers);

    // Print the vector with tab separators:
    std::copy(numbers.begin(), numbers.end(),
            std::ostream_iterator<int>(std::cout, "\t"));
    std::cout << std::endl;

    return 0;
}

struct CalcMaxInt
{
    int maxInt;
    CalcMaxInt () : maxInt(0) {}
    void operator () (int i) { if (i > maxInt) maxInt = i; }
};

void CountingSort(vector<int>& numbers)
{
    CalcMaxInt cmi = std::for_each(numbers.begin(), numbers.end(), CalcMaxInt());
    //int maxInt = cmi.maxInt + 1;
    int maxInt = 130001;

    vector <int> temp1(maxInt);
    vector <int> temp2(maxInt);

    for (int i = 0; i < numbers.size(); i++)
    {
        temp2[numbers[i]] = temp2[numbers[i]] + 1;
    }

    for (int i = 1; i <= maxInt; i++)
    {
        temp2[i] = temp2[i] + temp2[i - 1];
    }

    for (int i = numbers.size() - 1; i >= 0; i--)
    {
        temp1[temp2[numbers[i]] - 1] = numbers[i];
        temp2[numbers[i]] = temp2[numbers[i]] -1;
    }

    for (int i =0;i<numbers.size();i++)
    {
        numbers[i]=temp1[i];
    }
    return;
}

3 个答案:

答案 0 :(得分:2)

您正在尝试访问超出适当范围的元素。 temp2的范围为[0 ... maxInt-1],但以下代码使用的temp2 [maxInt]超出范围。

for (int i = 1; i <= maxInt; i++)
{
    temp2[i] = temp2[i] + temp2[i - 1];
}

你必须修复temp2才能拥有maxInt + 1个元素或者i&lt; maxInt不要看错误。

答案 1 :(得分:1)

这不是你这样做的全部要点:

 CalcMaxInt cmi = std::for_each(numbers.begin(), numbers.end(), CalcMaxInt()); 

获取最大元素?

我将您的代码更改为以下内容。

void CountingSort(vector<int>& numbers)  
{  
    CalcMaxInt cmi;
    std::for_each(numbers.begin(), numbers.end(), cmi);          
    int maxInt = cmi.maxInt;

    vector <int> temp1(maxInt);    
    vector <int> temp2(maxInt);  

    // then the rest the same starting with the for loops
    // but with the fix that @kcm1700 mentioned to the for loop
} 

答案 2 :(得分:0)

不应该temp1标注numbers.size()+1