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 ()
{
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;
you can something like this 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);
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
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.
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.
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).
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.
To declare a 2D array using std::vector
, you can use this kind of construction:
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
.
It's basically a nesting of the "initialise with n
items of value val
" constructor:
vector (size_type n, const value_type& val,
const allocator_type& alloc = allocator_type());
(constructor definition copied from here)
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.
If you know the elements beforehand then you could just do
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.