There are several ways to define a 2D array in C++ and STL without memory manipulation, and the following codes illustrate two different methods:
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!
In C++11 use std::array
:
std::array<std::array<int,3>,2> a {{
{{1,2,3}},
{{4,5,6}}
}};
Some usage:
a[0][2] = 13;
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.
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.
One very efficient method to define arrays is dynamic allocation, using the new
and delete
operators. Here is an example:
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With