一个 2D 数组,并按行存储值.第一个循环用于行索引,第二个循环用于列索引

A 2D array and storing the values row-wise. The first loop is for row index and 2nd loop for column index

本文关键字:用于 循环 索引 第二个 第一个 存储 数组 2D 一个      更新时间:2023-10-16

我刚开始 c++

下面是 2D 数组的代码,并按行存储值。第一个循环用于行索引,第二个循环用于列索引,我也在 arr[x][y] 和 arr[col] 中出现错误

#include <iostream>
using namespace std;
int main()
{
int x, y;
int arr[x][y];
cout << "Enter row number and column number :";
cin >> x >> y;
int row, col;
cout << "Enter value of arrayn";
for (int row = 0; row < x; ++row)
{
for (int col = 0; col < y; ++col)
{
cin >> arr[row][col] << " ";
}
}
cout << "Value of array are:n";
for (row = 0; row < x; row++)
{
for (col = 0; col < y; col++)
{
cout << arr[row] << arr[col] << " ";
}
cout << "n";
}
return 0;
}

问题 1:顺序很重要。

int x, y; // x and y have undefined values
int arr[x][y]; // attempts to dimension an array with undefined values.
cout << "Enter row number and column number :";
cin >> x >> y; // now we have x and y values. 

溶液:

int x, y; // x and y have undefined values
cout << "Enter row number and column number :";
cin >> x >> y; // now we have x and y values. 
int arr[x][y]; // can now dimension array

问题 2:非标准代码

数组只能使用标准C++中的常量值进行标注

int arr[x][y]; // fails on many compilers. 
// Don't be angry, they are following the language rules.

造成这种情况的原因有很多。在我看来,最大的问题是它们很难控制程序使用的自动内存量。输入 2000 进行xy,并观看程序以有趣且通常奇怪的方式失败。

溶液:

在此处使用std::vector

vector<vector<int>> arr(x, vector<int>(y));

注意:

vectorvector由于空间局部性低,性能较差。每个vector都包含自己的存储块,位于动态内存中的某个位置,每次程序从一个vector移动到另一个时,都必须查找和加载新vector的数据。

如果这是一个问题,请使用此处所述的单一vector方法。

问题 3:写入输入流

cin >> arr[row][col] << " ";

cin读取到arr[row][col] and then attempts to write" "to the stream.cin' 是仅输入的,无法写入。

溶液:

由于您可能根本不需要此写入,>>根据空格分隔自动分隔标记,因此我们可以安全地丢弃写入。

cin >> arr[row][col];

问题 4:写入数组而不是数组中的数据

cout << arr[row] << arr[col] << " ";

将数组中的一行而不是单个数据值写入arr[row]cout。然后它将数组中的另一行arr[col]写入cout

溶液:

要在arr[row][col]处写入值,我们需要从字面上做到这一点

cout << arr[row][col] << " ";

我认为这大约涵盖了它。

推荐阅读

为什么是"使用命名空间 std;"被认为是不良做法?

一个很好的C++参考文本。无论你现在从中学到什么,都不会对你有任何好处。