一个 2D 数组,并按行存储值.第一个循环用于行索引,第二个循环用于列索引
A 2D array and storing the values row-wise. The first loop is for row index and 2nd loop for column index
我刚开始 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 进行x
和y
,并观看程序以有趣且通常奇怪的方式失败。
溶液:
在此处使用std::vector
。
vector<vector<int>> arr(x, vector<int>(y));
注意:
vector
的vector
由于空间局部性低,性能较差。每个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++参考文本。无论你现在从中学到什么,都不会对你有任何好处。
相关文章:
- 用于循环编译的 constexpr
- C++用于循环跳过向量的元素?
- OpenMP 内部的函数调用用于循环
- 用于循环访问多个集合的数据结构
- Leetcode C++用于循环条件
- fworldperscreenwidththpixel如何用于循环绘制
- C 迭代用于循环并在其中调用功能
- 在C 中打印矩阵二级对角线,用于循环
- 简单的C 嵌套以用于循环程序,以打印带有星星错误的正方形
- 使用4用于循环的4矩阵上的数组下标的“ int [int]类型”
- 用于循环,if表示Ardiuno驱动湿度控制的说明
- C++ 用于循环后增量前增量差异
- 将C 17支持基于较简单的范围用于循环
- 为什么我的if语句不适用于循环
- 使用基于自动的范围用于循环VS,使用对循环范围的基于对的范围
- 使用用于循环C 的字符串反转
- 用于循环范围范围
- 用于循环的c++(c++11方式和旧版本方式)
- c++amp:复合类型,用于循环,在GPU上声明
- 括号内用于循环初始化