Array Initialization
What are the different ways to initialize a std::array
in C++?
There are several ways to initialize a std::array
in C++:
Default initialization
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;
Initialization with specific values
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};
Initialization with fewer values than the array size
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};
Initialization with class template argument deduction (CTAD)
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};
Default initialization with empty braces
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.
Static Arrays using std::array
An introduction to static arrays using std::array
- an object that can store a collection of other objects