-1
#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 ?

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
enami
  • 1
  • 1
  • What don't you understand about it exactly? – ShadowMitia Nov 25 '21 at 15:04
  • 1
    It seems to be missing the `std::` namespace qualifier. – paddy Nov 25 '21 at 15:05
  • to declare an array it should be like this type_name array[][], i don't understand the way it was declared like that – enami Nov 25 '21 at 15:06
  • 3
    You can read about the `array` template here: https://en.cppreference.com/w/cpp/container/array -- in general, bookmark cppreference.com in your browser, and go there any time you are looking for information on C++. – paddy Nov 25 '21 at 15:07
  • 1
    std::array has advantages over the c arrays: [https://stackoverflow.com/questions/30263303/stdarray-vs-array-performance](https://stackoverflow.com/questions/30263303/stdarray-vs-array-performance) – drescherjm Nov 25 '21 at 15:09

1 Answers1

0

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.

digito_evo
  • 3,216
  • 2
  • 14
  • 42