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

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Passing Arrays by Reference
Why is it more efficient to pass a std::array by reference to a function instead of by value?
Out-of-Bounds Array Access
What happens if I try to access an element in a std::array using an index that is out of bounds?
Changing Array Size
Can I change the size of a std::array after it has been created?
std::array vs C-style Arrays
What are the advantages of using std::array over traditional C-style arrays?
Accessing Elements in Nested Arrays
How do I access elements in a multidimensional std::array?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant