There are several ways to initialize a std::array
in C++:
In this example, we create an array of 5 integers, with each element default-initialized. For int
, this means they are initialized with a value of 0
:
std::array<int, 5> MyArray;
This creates an array of 5 integers, with the elements initialized to the specified values:
std::array<int, 5> MyArray{1, 2, 3, 4, 5};
Below, we provide initialisation for some of the values. The remaining elements will be value-initialized. For primitive types like int
, this means they will be zero-initialized.
std::array<int, 5> MyArray{1, 2, 3};
In this example, the compiler deduces the type and size of the array based on the initializer list.
std::array MyArray{1, 2, 3, 4, 5};
In the following example, all elements will be value-initialized (zero-initialized in the case of int
):
std::array<int, 5> MyArray{};
Remember that std::array
has a fixed size known at compile time, so you must specify the size when declaring the array, unless you use CTAD.
Answers to questions are automatically generated and may not have been reviewed.
std::array
An introduction to static arrays using std::array
- an object that can store a collection of other objects