use*_*544 2 c++ arrays user-input multidimensional-array
我是编程的新手,所以我想写一个代码,让我输入一个二维数组(或我的情况下的矩阵),然后打印它.
#include <iostream>
using namespace std;
void printArray( const int *array, int count )
{
for ( int i = 0; i < count; i++ )
cout << array[ i ] << " ";
cout << endl;
}
int main () {
int n;
cout<<"Please enter the length of your matrix : "<<endl;
cin>>n;
int * y=new int [n];
for (int w = 0; w <= n-1; w++ ) {
y[w] = new int [n];
cout<<"Insert the elements ";
for (int z = 0; z <= n-1; z++)
{
cin >>y [w][z];
}
}
printArray(y, n);
}
Run Code Online (Sandbox Code Playgroud)
但是我得到的错误如"从'int*'到'int'的无效转换"和"无效的类型int [int] for array subscript".能否请您查看我的代码并指出我的缺陷?
谢谢
您声明y
为int*
这只会是一维的.您将需要申报y
的int**
为它是2维的.
您的代码无法编译的原因是因为int* y
指向单个内存块(即整数数组,换句话说,是一堆int
s.).y[w]
是int
这个数组中的一个,所以y[w] = new int[n]
无法编译,因为你试图分配int*
一个int
.
改变y
到int**
该装置y
可以指向的数组int*
秒.由于每个都int*
可以指向一个数组int
,因此您将拥有一个二维数组.
10x10矩阵的示例代码int**
:
int** iShouldUseStdVector = new int*[10]; // allocate 10 int* <--
for (int i = 0; i < 10; i++)
{
iShouldUseStdVector[i] = new int[10]; // allocate 10 int <--
for (int k = 0; k < 10; k++)
{
iShouldUseStdVector[i][k] = k;
}
}
Run Code Online (Sandbox Code Playgroud)
10x10矩阵的示例代码std::vector
:
std::vector<std::vector<int>> thisIsEasy;
for (int i = 0; i < 10; i++)
{
thisIsEasy.push_back(std::vector<int>());
for (int k = 0; k < 10; k++)
{
thisIsEasy[i].push_back(k);
}
}
Run Code Online (Sandbox Code Playgroud)
我建议使用,std::vector<std::vector<int>> y;
因为它可以通过方便地增长来处理内存,因为你想要添加更多的元素并在它被破坏时释放内存.