[英]Generating an NxN magic square using a dynamically allocated 2D array in C++ with user-input dimension
[英]How can I create a square 2d array of size NxN where N is supplied by the user and populated with random numbers at a certain range?
我的目標是讓用戶輸入 3 到 8 范圍內的數字,它將根據該大小創建矩陣,然后用 -12 到 8 范圍內的隨機數填充它。
例如,如果用戶輸入 3
它應該顯示:
9 1 -4
4 2 -6
-11 5 8
我想我的概念是正確的,但可變長度數組讓我感到困惑,因為我知道除非您使用 std:vector,否則不可能創建一個不是常量的數組,但我不知道如何在這段代碼中實現它。
我不斷收到錯誤“下標需要數組或指針類型”
#include<iostream>
#include <random>
#include<time.h>
#include<iomanip>
#include <vector>
#include <map>
using namespace std;
void array_gen(int* array, int arraysize) // void function to generate the array with random numbers
{
int i;
for (i = 0;i < arraysize;i++)
{
array[i] = rand() % -12 + 8; // used to generate numbers from 0 to 10
}
}
void arraydis(int* array, int arraysize) // function to sort array
{
int i;
for (i = 0;i < arraysize;i++)
{
for (int j = 0; j < arraysize;j++)
{
std:cout << array[i][j];
}
}
}
int main()
{
int arraysize = 0, i;
cout << "Enter array in the range of 50 <= size <= 200: "; // records the users input
cin >> arraysize;
int* array = new int[arraysize], freq[10];
array_gen(array, arraysize);
cout << "unSorted array is:"; // shows the unsorted array
arraydis(array, arraysize);
}
您可能應該使用 int 向量的向量,使用std::vector
。
#include<iostream>
#include <random>
#include<time.h>
#include<iomanip>
#include <vector>
#include <map>
using namespace std;
// generate the array with random numbers
void array_gen(vector<vector<int>> & array, size_t arraysize)
{
array.resize(arraysize);
for (auto& line : array)
line.resize(arraysize);
for (size_t i = 0; i < arraysize; i++)
{
for (size_t j = 0; j < arraysize; j++)
{
array[i][j] = rand() % -12 + 8; // generate numbers from 0 to 10
}
}
}
void arraydis(const vector<vector<int>> & array)
{
for (size_t i = 0; i < array.size(); i++)
{
for (size_t j = 0; j < array.size(); j++)
{
cout << array[i][j] << " ";
}
cout << "\n";
}
}
int main()
{
int arraysize = 0, i;
cout << "Enter array in the range of 50 <= size <= 200: "; // records the users input
cin >> arraysize;
vector<vector<int>> array;
array_gen(array, arraysize);
cout << "unSorted array is:\n"; // shows the unsorted array
arraydis(array);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.