计数排序无限循环
Counting Sort infinite loop
我正在编写一个计数排序函数,当我运行它时,会弹出一个窗口,说"文件名.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;
}
您正在尝试访问超出正确范围的元素。temp2 的范围 [0...maxInt-1],但以下代码使用超出范围的 temp2[maxInt]。
for (int i = 1; i <= maxInt; i++)
{
temp2[i] = temp2[i] + temp2[i - 1];
}
您必须修复 temp2 以具有 maxInt+1 元素,或者 i
你这样做的全部意义不就是:
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
}
temp1
不应该被标注numbers.size()+1
?
相关文章:
- 过载'operator new'如何导致无限循环?
- C++正则表达式无限循环
- 程序在尝试猜测它选择的随机数时进入无限循环?
- 遍历链表时的无限循环
- 循环链表:无限循环
- 比较两个字符串后卡在无限循环中
- 在做一段时间内检查字符的无限循环
- 逐字读取文本文件中的每一行并转换为 int(无限循环或崩溃?
- 在这个无限循环中,当输入 0 时终止,当输入 int 范围之外的任何内容时,程序行为不正常
- 可能的无限循环
- 超出 int 的值范围后的无限循环
- 为什么这段代码会导致无限循环?
- 运行无限循环的最小二叉树问题
- 单排序链表-无限循环
- 计数排序无限循环
- 有什么更有效的方法来确保我不会在这个快速排序函数中陷入无限循环?(C++)
- 快速排序应用于指向对象的指针向量-无限循环
- c++递归快速排序无限循环
- 快速排序中的无限循环
- 快速排序无限循环数值配方