C++ 中的二维整数数组,每行中的元素数量不均匀



这个数组的行数和列数由用户给出,但行数不相同(数组不均匀(,用户也将通过输入元素来填充数组。

这是我编写的代码,但是当我尝试从用户那里获取输入时,代码在接受一些输入后崩溃。请您帮助我并纠正我的代码并指出我的缺陷。谢谢。

#include <iostream>
//2d array
using namespace std;
int main()
{
int row;
int col_x;
cout << "Enter the row number:" << endl;
cin >> row;
//cout<<"Enter the column number:"<<endl;
//cin>>col;
int **a = new int *[row];
for (int r = 0; r < row; r++)
{
cout << "Enter the column no.of array " << r << endl;
cin >> col_x;
a[r] = new int[col_x];
cout << "Enter the elements in the array:" << endl;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col_x; j++)
{
cin >> a[i][j];
}
}
cout << "The elements in the array:" << endl;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col_x; j++)
{
cout << a[i][j] << " ";
}
cout << endl;
}
}
delete[] a;
a = NULL;
return 0;
}

有一个额外的 for 循环。此外,您必须存储每行的大小。 并对 2D 数组进行适当的分配。

#include <iostream>
//2d array
using namespace std;
int main()
{
int row;
cout<<"Enter the row number:"<<endl;
cin>>row;
int **a=new int *[row];
int *col_x = new int [row];
for(int r=0;r<row;r++){
cout<<"Enter the column no.of array "<<r<<endl;
cin>>col_x[r];
a[r]=new int[col_x[r]];
cout<<"Enter the elements in the array:"<<endl;
for(int j=0;j<col_x[r];j++){
cin>>a[r][j];
}
}
cout<<"The elements in the array:"<<endl;
for(int i=0;i<row;i++){
for(int j=0;j<col_x[i];j++){
cout<<a[i][j]<<" ";
}
cout<<endl;
}
for (int i=0; i<row; ++i)
delete[] a[i];
delete []a;
delete []col_x;
return 0;
}

您从用户那里获取输入的方式非常模糊,并且容易访问无效内存。您在内部循环中多次获得同一行。 尝试这样的事情:

#include <iostream>
//2d array
using namespace std;
int main() {
int row;
int col_x;
cout << "Enter the row number:" << endl;
cin >> row;
//cout<<"Enter the column number:"<<endl;
//cin>>col;
int ** a = new int * [row];
for (int r = 0; r < row; r++) {
cout << "Enter the column no.of array " << r << endl;
cin >> col_x;
a[r] = new int[col_x];
cout << "Enter the elements in the array:" << endl;
for (int j = 0; j < col_x; j++) {
cin >> a[r][j];
}
}
cout << "The elements in the array:" << endl;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col_x; j++) {
cout << a[i][j] << " ";
}
cout << endl;
}
delete[] a;
a = NULL;
return 0;
}

另请注意,col_x将仅保存最后一行的大小。因此,它不适用于代码末尾的打印。

不确定您要实现的目标,但上述代码的主要问题是,您正在访问数组中不存在的元素。也许您在r上的循环应该以第 18 行结束?即便如此,您也必须将每行的列数存储在某个外部变量中。我建议使用std::vector作为容器而不是固定数组,在您的情况下是std::vector< std::vector<int> >.向量类有一个方法size()用于存储其实际大小。

由于您使用的是C++,因此您应该利用它为您提供的容器来存储数据,在这种情况下,向量向量是合适的:

现场样品

#include <iostream>
#include <vector>
using namespace std; //<-- for test, souldn't be used
int main() {
int rows, cols, temp;
vector<vector<int>> matrix;
cout << "Enter the row number:" << endl;
cin >> rows;
for (int i = 0; i < rows; i++){
vector<int> v;
cout << "Enter the column no.of array " << i << endl;
cin >> cols;
cout << "The elements in the array:" << endl;
for (int j = 0; j < cols; j++){
cin >> temp;
v.push_back(temp);
}
matrix.push_back(v);
}
cout << endl;
for( auto i: matrix){   //print results
for(int j: i)
cout << j << " ";
cout << endl;
}
}

最新更新