在尝试使用此代码实现组快速选择算法时,我遇到了这个非常奇怪的问题。我使用2D动态分配的数组将各个元素保存在随机生成的10个数字的未排序数组的组中。当我运行组大小为2,5或10的代码时,它可以很好地工作。但是当我将组大小更改为一个会使一个组小于其他组的数字时,当我尝试将数组的内容初始化为某些测试数据时,它会中断。谢谢你的任何建议。
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <random>
#include <array>
using namespace std;
int groupSize = 0;
int groupSelect(int *, int, int, int);
int main()
{
// randomize array of size 10 with entries between 1 and 20.
random_device rd;
mt19937 eng(rd());
uniform_int_distribution<> distr(1, 20);
int max = 10;
int * Array;
Array = new int[max];
for (int i = 0; i < max; i++)
{
Array[i] = distr(eng);
}
// display array contents (unsorted)
cout << "Array contents are:\n";
for (int i = 0; i < max; i++)
{
cout << Array[i] << ", ";
}
cout << endl;
/*------------------------------------------------------------------------------*/
groupSize = 3;
int poo = groupSelect(Array, 0, 9, 5);
return 0;
/*------------------------------------------------------------------------------*/
delete[] Array;
}
int groupSelect(int* arr, int start, int end, int k)
{
bool remainder = false;
int size = 10;
if ((size % groupSize) != 0)
{
remainder = true;
}
//size = amount of groups of 5 (and remainder group)
size = size - (size % groupSize);
size = size / groupSize;
if(remainder)
size++;
cout << "Size = " << size << endl;
int** groups = new int*[size];
for (int i = 0; i < size; ++i)
{
if (remainder == true)
{
if (size - i == 1)
groups[i] = new int[((size) % (groupSize))];
}
else
groups[i] = new int[groupSize];
}
int testV = 0;
for (int i = 0; i < size; i++)
{
int temp = groupSize;
if (size - i == 1)
{
if (remainder)
temp = size % groupSize;
}
for (int j = 0; j < temp; j++)
{
groups[i][j] = testV; // codes break here
testV++;
}
}
cout << "\nGroup arrays' contents\n" << endl;
for (int i = 0; i < size; i++)
{
for (int j = 0; j < groupSize; j++)
{
cout << "groups[" << i << "]["<<j<<"] contents = " << groups[i][j] << endl;
}
}
delete[] groups;
return 0;
}
答案 0 :(得分:0)
你有一个错误:如果余数为真但大小为1!= 1你永远不会初始化你的数组然后你试图访问它们
for (int i = 0; i < size; ++i)
{
if (remainder == true)
{
if (size - i == 1)
groups[i] = new int[((size) % (groupSize))];
}
else
groups[i] = new int[groupSize];
}