【发布时间】:2016-12-11 03:06:57
【问题描述】:
程序编译,我可以输入一个数字,但它不生成或显示数组。当我在 randomFillUnique 函数中使用线性搜索取出 while 条件时,它会生成并显示数组,但不是唯一的数字。我需要一个没有重复数字的二维数组。
#include <iostream>
#include <string>
#include <random>
#include <ctime>
using namespace std;
int** gen2Array(int n);
void randomFillUnique(int** arr, int n);
bool lSearch(int** arr, int n, int target);
void display(int** arr, int n);
int main()
{
int number;
cout << "Enter a number: ";
cin >> number;
randomFillUnique(gen2Array(number), number);
system("pause");
return 0;
}
int** gen2Array(int n)
{
int** arr2D = new int*[n];
for (int index = 0; index < n; index++)
arr2D[index] = new int[n];
return arr2D;
}
void randomFillUnique(int** arr, int n)
{
static default_random_engine e;
uniform_int_distribution<int> u(1, n*n);
e.seed(static_cast<int>(time(NULL)));
bool result = false;
for (int row = 0; row < n; row++)
{
for (int col = 0; col < n; col++)
{
arr[row][col] = u(e); //generate random number
result = lSearch(arr, n, arr[row][col]);
while (result == true)
{
arr[row][col] = u(e); //generate random number
result = lSearch(arr, n, arr[row][col]);
}
}
}
display(arr, n);
delete[] arr;
}
bool lSearch(int** arr, int n, int target)
{
bool found = false;
for (int row = 0; row < n; row++)
for (int col = 0; col < n; col++)
{
if (arr[row][col] == target)
{
found = true;
return found;
}
}
return found;
}
void display(int** arr, int n)
{
for (int row = 0; row < n; row++)
{
for (int col = 0; col < n; col++)
cout << arr[row][col];
cout << endl;
}
}
【问题讨论】:
-
因为您将 arr[row,col] 设置为 u(e),它总是会在数组中找到该值,而您在 lsearch 中的 while 循环会永远循环
-
与其随机选择一个数字并拒绝重复,不如考虑在一组可能性中创建一个
std::vector,然后应用std::shuffle来随机化vector。然后从vector中挑选前N个元素 -
离题:内存泄漏。
delete[] arr;删除外部数组但不删除内部数组。现在没有任何东西指向内部数组,因此它们非常难以删除。 -
@user4581301 谢谢你,但是对于这个任务,我的任务是用默认的 void randomFillUnique(int** arr, int n) 随机填充数组。感谢您的内存泄漏建议。我会马上解决的。
-
知道了。将做出解释技术的答案。使用它可能会惹恼您的讲师,这取决于讲师,这可能是值得的。
标签: c++ arrays algorithm multidimensional-array linear-search