提问人:nub 提问时间:11/14/2023 最后编辑:Chrisnub 更新时间:11/14/2023 访问量:89
如何对两个维度数组使用嵌套的 FOR 循环?(C++)[关闭]
how do i use nested for loops for two dimentional arrays? (C++) [closed]
问:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const int NUM_ROWS = 5;
const int NUM_COLS = 10;
int array[NUM_ROWS][NUM_COLS]{};
cout << "Array contents:" << endl;
for (int row = 0;row<NUM_ROWS;row++)
{
for (int col=0;col<NUM_COLS;col++)
{
int array[row][col] = rand () % 200;
cout << array[row][col] << setw(2);
}
}
}
'我想使用 0 行和 199 列输入一个介于 10 之间的随机数(总共有 50 个随机数值),但我的 IDE 将 int 值:row 和 col 注册为常规变量,我认为可以迭代数组的维度。”
答:
1赞
ComicSansMS
11/14/2023
#1
这条线
int array[row][col] = rand () % 200;
语法无效。前导使它成为新局部变量的声明(遮蔽了 的第三行的外部声明),但初始值设定项对于初始化数组无效,因此您将收到编译器错误。int
array
main()
rand() % 200
删除前导以将此声明转换为赋值,程序将编译:int
array[row][col] = rand () % 200;
评论
3赞
Pete Becker
11/14/2023
它也是无效的,因为数组维度不是编译时常量。
2赞
Pepijn Kramer
11/14/2023
#2
与其使用“C”样式数组,不如看看 C++ 的数组(以及基于范围的 for 循环)
#include <array>
#include <random>
#include <iostream>
//using namespace std; // no do not us this
int main()
{
// C++ random generation
std::random_device entropy_source{};
std::mt19937 random_generator{ entropy_source() };
std::uniform_int_distribution<int> distribution{ 0,199 };
//C++ 2D array
// with C++ arrays you can pass them around like objects
// and return them from functions (instead of using raw pointers
// and running into "C" style pointer decay and memory allocation unclarities)
std::array<std::array<int, 10>, 5> values;
//C++ arrays keep track of their own size of use later
std::cout << "number of rows = " << values.size() <<"\n";
// prefer range based for loops, they cannot go out of bounds
for (auto& row : values)
{
for (auto& value : row)
{
value = distribution(random_generator);
std::cout << value << " ";
}
std::cout << "\n";
}
return 0;
}
评论
0赞
463035818_is_not_an_ai
11/14/2023
您还应该指出 OP 所犯的错误。他们可以用std::array<std::array<int, 10>, 5>
0赞
Pepijn Kramer
11/14/2023
很公平;)但至少他不能写 ' int array[row][col] = rand () % 200;' 因为只有赋值value
0赞
463035818_is_not_an_ai
11/14/2023
int value = rand() % 200;
;)
0赞
Pepijn Kramer
11/14/2023
Nope ;)例如 godbolt.org/z/9sf9EPx5c(错误:重新声明“int value”x86-64 gcc 13.2 #1)。对于其他编译器/版本,请始终在启用所有警告的情况下进行编译。
0赞
463035818_is_not_an_ai
11/14/2023
确定这是一个错误,就像 OP 代码有错误一样(但他们不理解错误消息,这就是问题的原因)
评论