简体   繁体   English

双数组,大小作为用户输入

[英]Double array with size as user input

I want to do something like this 我想做这样的事情

int n,m; //or cin>>n>>m;

a[n][m];

//then do whatever with the array

The problem is that Visual Studio gives me errors, while dev c++ doesn't. 问题是Visual Studio给我错误,而dev c ++没有。 I want to compile it in VS. 我想在VS中编译它。

Even if your compiler supports VLA(Variable Length Arrays), you didn't declared a properly: 即使你的编译器支持VLA(变长数组),你没有宣布a正确:

int a[n][m];
^^^

You should use std::vector which is a standard way 您应该使用std::vector这是一种标准方式

std::vector<std::vector<int> > a(n, std::vector<int>(m));

That depends on the compiler... 这取决于编译器...
Use of std::vector is always recommended for such need. 对于此类需求,始终建议使用std::vector
But if you have to , then you can allocate that memory on the heap like this... 但是,如果必须这样做 ,则可以像这样在堆上分配该内存...

using new (recommended in C++)... 使用new (在C ++中推荐)...

cout << "Enter n & m:";
int n, m;
cin >> n >> m;

int** p = new int*[n];
for (int i = 0 ; i < n; i++) {
    p[i] = new int[m];
}

or using malloc (Do it in C. Not recommended in C++)... 或使用malloc (在C中执行。不建议在C ++中使用)...

cin >> n >> m;

int** p = (int**) malloc (n * (int*));

for (int i = 0; i < n; i++) {
    p[i] = (int*) malloc(m * (int));
}

for a 2D array of int s. 用于int的2D数组。

But remember to delete or free it after your use. 但是请记住在使用后将其deletefree

You could use a std::vector<Type>(n*m) , that would probably be the nicest way. 您可以使用std::vector<Type>(n*m) ,这可能是最好的方法。

If however you want to stay with the array, I guess that it would compile if you allocate the memory on the Heap instead of the stack by calling new/malloc. 但是,如果您想继续使用该数组,我想如果您通过调用new / malloc在堆上而不是堆栈上分配内存,它将可以编译。 But remind yourself of freeing the memory afterwards and please check the user input before you do it to prevent malicious inputs. 但是请提醒自己,释放内存之后,请在操作之前检查用户输入,以防止恶意输入。

array needs constant paras. 数组需要常量paras。

instaead, you can use vector< vector <int> > 可以使用vector< vector <int> >

Variable length arrays are proposed in the upcoming C++14 standard , but not yet in the language. 在即将到来的C ++ 14标准中提出了可变长度数组 ,但尚未在该语言中提出。

You can however use a std::vector of std::vector of whatever type you want. 但是,您可以使用任意类型的std::vectorstd::vector

Like 喜欢

std::vector<std::vector<int>> a(n, std::vector<int>(m));

The above declaration create a vector of vectors of integers, the outer vector of size n and the inner vector of size m . 上面的声明创建了一个由整数向量,大小为n的外部向量和大小为m的内部向量组成的向量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM