简体   繁体   English

C ++多维数组

[英]C++ multi-dimensional array

We have the code: 我们有以下代码:

int arr[3][4];

So arr is: 所以arr是:

  1. An array of 3 elements, and every element is an array of 4 int. 3个元素组成的数组,每个元素都是4个int组成的数组。

  2. An array of 4 elements, and every element is an array of 3 int. 一个4个元素的数组,每个元素都是3个int的数组。

which one is right and why? 哪一个是正确的,为什么? How does it work with higher dimensional array? 它如何与高维数组一起工作? I suppose this is concerning operator precedence and associativity. 我想这与操作符的优先级和关联性有关。

Your first interpretation is correct. 您的第一个解释是正确的。

Such declarations are best parsed using the Right Left rule , which you can read here and here 最好使用Right Left规则解析此类声明,您可以在此处此处阅读

$8.3.4 from the C++ draft Standard: ... C ++草稿标准中的$ 8.3.4:...

Example: consider int x[3][5]; 示例:考虑int x [3] [5]; Here x is a 3 × 5 array of integers. 这里x是3×5的整数数组。

... ...

Note: It follows from all this that arrays in C++ are stored row-wise (last subscript varies fastest) and that the first subscript in the declaration helps determine the amount of storage consumed by an array but plays no other part in subscript calculations. 注意:由此可见,C ++中的数组是按存储 (最后一个下标变化最快),声明中的第一个下标有助于确定数组消耗的存储量,但在下标计算中不起作用。 —end note ] —尾注]

Note C++ does not have operator[][]. 注意C ++没有运算符[] []。 It has only operator[] 它只有运算符[]

I find it easiest to think of the "rows" and "columns" in a multidimensional array rather than trying to get my mind around "arrays of arrays". 我发现最容易想到多维数组中的“行”和“列”,而不是试图使我的注意力集中在“数组数组”上。 This has the convenient property that I decide which index is the rows and which is the columns. 这具有方便的属性, 可以确定哪个索引是行,哪个索引是列。 In other words, I can think of int arr[3][4]; 换句话说,我可以想到int arr[3][4]; as a 2D array either with 3 rows and 4 columns or with 4 rows and 3 columns. 作为具有3行4列或4行3列的2D数组。 As long as my code is consistent with my mental view of the array, all will work out fine. 只要我的代码与我对数组的看法一致,那么一切都会顺利进行。 However, if half-way through a program I switch views, things will start breaking. 但是,如果我在程序中途切换视图,事情就会开始崩溃。

With that said, usually I prefer to think of this example as 3 rows and 4 columns since this is similar to the mathematical notation in linear algebra where rows are listed first. 话虽如此,通常我更喜欢将此示例视为3行4列,因为这类似于线性代数中首先列出行的数学符号。

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

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