我从C(ANSI)跳进C++ 11.这确实是一个奇怪的世界.
我正试图解决以下问题:
int tbl[NUM_ROWS][NUM_COLS] = { 0 };
for (auto row : tbl)
for (auto col : row) // ERROR - can't iterate over col (type int *)
// do stuff
Run Code Online (Sandbox Code Playgroud)
我猜测,这里的理性相当于(在C中)之间的差异:
int v[] = { 1, 2, 3, 4, 5 };
int *u = v;
// (sizeof v) != (sizeof u);
Run Code Online (Sandbox Code Playgroud)
但是,我不太清楚以下是如何工作的:
int tbl[NUM_ROWS][NUM_COLS] = { 0 };
for (auto &row : tbl) // note the reference
for (auto col : row)
// do stuff
Run Code Online (Sandbox Code Playgroud)
逻辑上,我正在考虑auto输入int * const- 这就是"数组"变量,一个指向(可能)非常量元素的常量指针.但是这比普通指针更加可迭代?或者,因为它row是一个引用,它实际上是键入的int [NUM_COLS],就像我们声明的row那样int row[NUM_COLS]?
C++中没有"多维数组".只有阵列.但是,数组的元素类型本身可以是数组.
当你说for (auto x : y),那么x是范围元素的副本.但是,无法复制数组,因此在y数组值数组时无效.相比之下,形成对数组的引用是完全正确的,这就是为什么for (auto & x : y)有效.
也许它有助于拼写出类型:
int a[10][5]; // a is an array of 10 elements of int[5]
for (int (&row)[5] : a)
for (int & cell : row)
cell *= 2;
Run Code Online (Sandbox Code Playgroud)