1
當試圖使用此代碼來實現組快速選擇算法時,我有這個非常奇怪的問題。我使用一個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;
}
不,它不是!還沒有完成,只要執行整個算法,我只需要幫助克服這個絆腳石訪問衝突 –