如何在没有内存操作的情况下在 C++ 和 STL 中定义二维数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12841170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to define a 2D array in C++ and STL without memory manipulation?
提问by feelfree
There are several ways to define a 2D array in C++ and STL without memory manipulation, and the following codes illustrate two different methods:
在 C++ 和 STL 中有几种方法可以在不进行内存操作的情况下定义二维数组,以下代码说明了两种不同的方法:
int main ()
{
/**************
1 2 3
4 5 6
***************/
// Method 1
const int ROW = 2;
const int COL = 3;
int array1[ROW][COL];
for(int i=0; i<ROW; i++)
for(int j=0; j<COL; j++)
array1[i][j] = i*COL+j+1;
// Method 2
typedef vector<vector<int> > ARRAY;
ARRAY array2;
vector<int> rowvector;
for(int i=0; i<ROW; i++)
{
rowvector.clear();
for(int j=0; j<COL; j++)
rowvector.push_back(i*COL+j+1);
array2.push_back(rowvector);
}
return 0;
}
My question is: are there other ways to define the 2D array? Which one is the most efficient one? Thanks!
我的问题是:还有其他方法可以定义二维数组吗?哪一种是最有效的?谢谢!
采纳答案by Heisenbug
are there other ways to define the 2D array?
还有其他方法来定义二维数组吗?
No without manipulating memory explicitely (malloc/free). If you use static allocated array (1st example) you allocate the space at compile time, so you can't add more rows or columns at runtime.
没有显式操作内存(malloc/free)。如果使用静态分配的数组(第一个示例),则在编译时分配空间,因此无法在运行时添加更多行或列。
The second example uses std::vector
that hides to you dynamic memory allocation . This way you can eventually add more rows or columns at runtime.
第二个示例使用std::vector
它向您隐藏动态内存分配。通过这种方式,您最终可以在运行时添加更多行或列。
If you don't need to dynamically modify the array dimension, then the first solution is the simpler and faster one (even if I think that std::vector implementation is fast enough to be comparable to static array, more elegant and more object oriented).
如果不需要动态修改数组维数,那么第一种方案是更简单更快的方案(即使我认为std::vector的实现速度足够快,可以媲美静态数组,更优雅,更面向对象) )。
If you need to modify the array dimension at run-time use std::vector, because it saves you from dealing directly with malloc and free.
如果您需要在运行时修改数组维度,请使用 std::vector,因为它可以避免您直接处理 malloc 和 free。
回答by PiotrNycz
In C++11 use std::array
:
在 C++11 中使用std::array
:
std::array<std::array<int,3>,2> a {{
{{1,2,3}},
{{4,5,6}}
}};
Some usage:
一些用法:
a[0][2] = 13;
回答by Rontogiannis Aristofanis
One very efficient method to define arrays is dynamic allocation, using the new
and delete
operators. Here is an example:
定义数组的一种非常有效的方法是使用new
和delete
运算符进行动态分配。下面是一个例子:
int **arr=new int*[ROW];
for( int i=0; i<ROW; ++i ) {
arr[i] = new int[COL];
for( int j=0; j<COL; ++j ) {
arr[i][j] = some_val;
}
}
The big advantage of this approach is that when you don't need any more the memory that the array uses, you can easily delete it. Here is an example of deleting a 2D array:
这种方法的一大优点是,当您不再需要数组使用的内存时,您可以轻松地将其删除。以下是删除二维数组的示例:
for( int i=0; i<ROW; ++i ) {
delete[] arr[i];
}
delete[] arr;
回答by japreiss
There are a lot of trade-offs here.
这里有很多权衡。
If you declare a C-style 2D array int array[height][width]
, then you really get a single contiguous block of memory. The compiler converts indexes to their 1D address
如果你声明一个 C 风格的 2D array int array[height][width]
,那么你真的会得到一个连续的内存块。编译器将索引转换为其一维地址
array[row][col] == *(array + row * width + col)
- Advantages: cache coherency. All the memory is in the same place.
- Disadvantages: you need a multiply for every indexing. Indirection might be faster.
- 优点:缓存一致性。所有的记忆都在同一个地方。
- 缺点:每个索引都需要乘法。间接可能会更快。
If you use a vector
of vectors
, then each row is allocated separately. The outer vector
stores pointers to the inner vectors
. Indexing becomes an indirection followed by an addition:
如果使用vector
of vectors
,则每一行都单独分配。外部vector
存储指向内部的指针vectors
。索引变成一个间接加法:
array[row][col] == *(*(array + row) + col)
- Advantages: indirection may be faster than multiplication.
- Disadvantages: not cache coherent, since each row is allocated separately (unless the implementation optimizes for
vector<vector>
).
- 优点:间接可能比乘法更快。
- 缺点:缓存不连贯,因为每一行都是单独分配的(除非实现针对 进行了优化
vector<vector>
)。
If performance is truly important, you need to test both and figure out which is faster on your data.
如果性能真的很重要,您需要对两者进行测试并找出哪个在您的数据上更快。
回答by David Rodríguez - dribeas
A common pattern is encapsulating the 2D array inside a class that offers the appropriate interface. In that case, you can use other internal representations, like for example a single vector of rows*cols
elements. The interface (usually operator()(int,int)
will map the coordinates from the caller to a position in the linear vector.
一种常见的模式是将二维数组封装在提供适当接口的类中。在这种情况下,您可以使用其他内部表示,例如单个rows*cols
元素向量。接口(通常operator()(int,int)
会将调用者的坐标映射到线性向量中的某个位置。
The advantage is that it has dynamic allocation, but a single allocation (unlike the std::vector<std::vector<int>>
where each vector must acquire it's own memory) and in a single block providing locality of data.
优点是它具有动态分配,但是是单一分配(与std::vector<std::vector<int>>
每个向量必须获取自己的内存的地方不同)并且在提供数据局部性的单个块中。
回答by MatthewD
To declare a 2D array using std::vector
, you can use this kind of construction:
要使用 声明二维数组std::vector
,您可以使用这种构造:
vector<vector<int> > matrix( n, vector<int>(m, -1) );
This creates a 2D array matrix
of size n
by m
, with all elements initialised to -1
.
这产生了2D阵列matrix
大小的n
通过m
,与初始化为所有元素-1
。
It's basically a nesting of the "initialise with n
items of value val
"constructor:
它基本上是“用n
值项初始化val
”构造函数的嵌套:
vector (size_type n, const value_type& val,
const allocator_type& alloc = allocator_type());
(constructor definition copied from here)
(构造函数定义从这里复制)
回答by kkg
If you know the elements beforehand then you could just do
如果你事先知道元素,那么你可以做
int arr[2][3] = {{1,2, 3}, {4, 5, 6}};
int arr[2][3] = {{1,2, 3}, {4, 5, 6}};
This should be more efficient than method1 and method2. Using vectors, you are not doing memory manipulation yourself, but the vector implementation will probably use a dynamically allocated array.
这应该比方法 1 和方法 2 更有效。使用向量,您不会自己进行内存操作,但向量实现可能会使用动态分配的数组。
回答by YounesCHTIOUI
you can something like this vector> m_2DArray;
你可以像这样 vector> m_2DArray;
then once you know the number of rows (rows) and number of columns (columns), you can resize your 2d array
然后一旦知道行数(行)和列数(列),就可以调整二维数组的大小
m_2DArray.resize(rows);
m_2DArray.resize(rows);
for(auto& el:m_2DArray) el.resize(columns);
for(auto& el:m_2DArray) el.resize(columns);
you can access data in the 2d array using m_2DArray[i][j], just like any other 2D array
您可以使用 m_2DArray[i][j] 访问二维数组中的数据,就像任何其他二维数组一样