C ++中的多维向量 [英] Multidimensional Vectors in C++
问题描述
我刚刚开始学习C ++.当我开始感到相当困惑时,我正试图掌握多维数组和向量的语法.我了解如何初始化多维数组.看起来很简单:行后跟列.但是,向量更具挑战性.我必须以相同的方式初始化它们还是创建向量的向量.有人请帮忙.
I just started learning C++. I was trying to grasp the syntax for multidimensional arrays and vectors when I started to get fairly confused. I get how to initialize multidimensional arrays. It seems straightforward: Rows followed by columns. However, vectors are a little more challenging. Do I have to initialize them in the same way or do I create a vector of vectors. Somebody please help.
推荐答案
如果您能够使用C ++ 11,则可以类似的方式初始化向量的多维数组和向量.
If you are able to use C++11, multidimensional arrays and vectors of vectors can be initialized in a similar manner.
int a1[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
std::vector<std::vector<int>> a2 = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
但是,在访问元素而不遇到未定义的行为时,必须理解一些差异.
However, there are differences that must be understood to access the elements without running into undefined behavior.
对于多维数组,需要连续分配数组元素的内存.对于向量的向量,元素的存储空间很可能是不相交的.
For a multidimensional array, memory for the elements of the array is required to be allocated contiguously. For a vector of vector, the memory for the elements is most likely going to be disjoint.
a1
的内存:
a1[0][0] a1[1][0] a1[2][0]
| | |
v v v
+---+---+---+---+---+---+---+---+---+
| | | | | | | | | |
+---+---+---+---+---+---+---+---+---+
a2
的内存(最有可能):
Memory for a2
(most likely):
a2[0][0]
|
v
+---+---+---+
| | | |
+---+---+---+
a2[1][0]
|
v
+---+---+---+
| | | |
+---+---+---+
a2[2][0]
|
v
+---+---+---+
| | | |
+---+---+---+
还可以定义一个向量的向量,其中每行的列数都不相同.
Also, it is possible to defined a vector of vectors in which the number of columns is not same for each row.
std::vector<std::vector<int>> a2 = { {1, 2, 3}, {4, 5}, {6, 7, 8, 9} };
在多维数组中,保证每一行的列数相同.
In a multidimensional array, the number of columns is guaranteed to be same for each row.
鉴于上述多维数组a1
,a1[1][2]
将是有效元素,而a1[2][3]
将是无效元素.对于向量的向量,使用上面的行,a2[1][2]
不是有效元素,a2[2][3]
是有效元素.
Given the above multidimensional array a1
, a1[1][2]
will be a valid element and a1[2][3]
will be an invalid element. In the case of a vector of vectors, using the above line, a2[1][2]
is not a valid element and a2[2][3]
is a valid element.
这篇关于C ++中的多维向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!