简体   繁体   English

C ++ 11多维数组的范围循环

[英]C++11 range-for loop over multidimensional array

I'm jumping into C++11 from C(ANSI). 我从C(ANSI)跳入C ++ 11。 It's a strange world indeed. 确实是一个陌生的世界。

I'm trying to come to grips with the following: 我正在尝试处理以下问题:

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

The rational here, I'm guessing, is equivalent to the difference between (in C): 我猜这里的合理性等效于(用C表示)之间的区别:

int v[] = { 1, 2, 3, 4, 5 };
int *u = v;
// (sizeof v) != (sizeof u);

However, I don't quite see how the following works: 但是,我不太了解以下工作原理:

int tbl[NUM_ROWS][NUM_COLS] = { 0 };
for (auto &row : tbl) // note the reference
  for (auto col : row)
    // do stuff

Logically, I'm thinking auto gets typed to int * const - thats what an "array" variable is, a constant pointer to a (possibly) non-constant element. 从逻辑上讲,我认为auto的类型为int * const这就是“数组”变量的含义,它是指向(可能是)非常量元素的常量指针。 But how is this any more iteratable than a normal pointer? 但是,与普通指针相比,它又如何可迭代的呢? Or, since row is a reference, it's actually typed to int [NUM_COLS] , just as if we declared row as int row[NUM_COLS] ? 或者,由于row是引用,因此实际上将其键入为int [NUM_COLS] ,就像我们将row声明为int row[NUM_COLS]

There are no "multi-dimensional arrays" in C++. C ++中没有“多维数组”。 There are only arrays. 只有数组。 However, the element type of an array can itself be an array. 但是,数组的元素类型本身可以是数组。

When you say for (auto x : y) , then x is a copy of the range element. 当您说for (auto x : y)x是range元素的副本 However, arrays cannot be copied, so that is not valid when y is an array-valued array. 但是,不能复制数组,因此当y是数组值的数组时无效。 By contrast, it is perfectly fine to form a reference to an array, which is why for (auto & x : y) works. 相比之下,形成对数组的引用是完全可以的,这就是为什么for (auto & x : y)有效的原因。

Maybe it helps to spell out the types: 也许有助于阐明类型:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM