std::array
is a C++ standard library container that stores a fixed number of elements of the same type in a single contiguous data structure in the memory. It is similar to a C++ native array, but with additional features and greater security.
The ideal is to abandon the C style of creating arrays and use std::array
.
std::array
std::array
is an attractive option for storing a fixed number of elements in a C++ program. Some benefits of using std::array
over other containers include:
std::array
provides index bounds checking at runtime, which means that an error will be thrown if you try to access an element outside the bounds of the array. This helps to avoid common programming errors such as improper memory access.std::array
To use std::array
in a C++ program, you must include the <array>
library and define an object of type std::array
with your specified size and element type. For example:
Similar to the array created above in C.
To print the elements, for example:
Or use the traditional
loop
.
You can also initialize the elements later, for example:
When printing all the other elements that have not been defined, they will have a value equal to ZERO:
0
.
std::array
has several member functions and iterators to make it easier to use, for example:
Check if the array is empty with .empty()
:
Among others as shown below:
For more information see this link.