#include <array>
array<array<bool,50>,9>coordinates{};
I saw this in a code but i didn't understand it, is it a different way to declare a 2d Arrays ?
#include <array>
array<array<bool,50>,9>coordinates{};
I saw this in a code but i didn't understand it, is it a different way to declare a 2d Arrays ?
std::array
is a struct template:
template<class T, std::size_t N> struct array;
It has several advantages over the C-style arrays according to cppreference.com as can be seen below:
The struct combines the performance and accessibility of a C-style array with the benefits of a standard container, such as knowing its own size, supporting assignment, random access iterators, etc.
Using C-style arrays you have to write it like bool coordinates[ 9 ][ 50 ] { };
. Here 9 is the number of rows and 50 is the number of columns.
Now let's take a brief look at some code. if you run this code:
#include <array>
int main( )
{
std::array< std::array<bool,50>, 9 > coordinates{ };
std::cout << sizeof( coordinates ) << '\n';
}
You will see:
450
This means that coordinates
takes up 9 * 50 == 450 bytes of memory on the stack. This type of array is not dynamically allocated (unlike e.g. std::vector
).
This:
// Prefer the upper one
std::cout << "Pointer to the underlying array: " << coordinates.data( ) << '\n';
std::cout << "Pointer to the underlying array: " << &coordinates << '\n';
will result in something similar to this:
Pointer to the underlying array: 0x8a651ff540
Pointer to the underlying array: 0x8a651ff540
But you should prefer coordinates.data( )
over &coordinates[0]
.
And also this:
std::cout << "Number of elements: " << coordinates.size( ) << '\n';
std::cout << "Maximum possible number of elements: " << coordinates.max_size( ) << '\n';
will give this:
Number of elements: 9
Maximum possible number of elements: 9
So as can be seen, unlike the conventional C arrays, the std::array
has many member functions that can assist the programmer. Not only that, but it's also safer to use. And last but not least, std::array
is equivalent to C arrays in terms of performance.