CodeBlanks Logo Icon CodeBlanks

std::array

Learn modern and safe array usage with std::array.

std::array

Since C++11, std::array is the modern, safe alternative to C-style arrays. It takes the size as a template parameter: std::array<int, 5> nums = {1, 2, 3, 4, 5};.

std::array is fixed-size like a C-style array and lives in memory the same way, but you can query its size with .size(), walk it safely with range-based for, and pass it by value to other functions. These features make it the preferred structure in modern C++ code.

The advantage of std::array

The biggest advantage of std::array is that it carries its size. With a C-style array you must keep the size in a separate variable, while with std::array nums.size() returns it directly. This helps prevent wrong index usage.

Also, std::array can be walked directly with range-based for as in for (int x : nums). When you pass a C-style array to a function it decays to a pointer and loses its size; std::array keeps that info. That is why new code prefers std::array.

Practice Print the std::array size

Declare a std::array as std::array<int, 5> nums = {10, 20, 30, 40, 50}; and print its size with std::cout << nums.size();. You must include the #include <array> header. The output must be 5.

Starter code

main.cpp
#include <iostream>
#include <array>

int main() {
    // Declare a std::array and print its size()
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <array>

int main() {
    std::array<int, 5> nums = {10, 20, 30, 40, 50};
    std::cout << nums.size() << std::endl;
    return 0;
}

Expected output

5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each std::array part to its role

Term Meaning
std::array Class template
<int, 5> Type and size
nums Variable name
.size() Size method

2 What does std::array<int, 3> a; a.size() return?

main.cpp
std::array<int, 3> a;
a.size()
  • 0
  • 1
  • 2
  • 3 Correct answer

Explanation: The size template parameter is 3; size() returns 3.

3 Write the std::array template parameter

Question
std::array<____> nums = {1, 2, 3, 4, 5};
Answer
std::array<int, 5> nums = {1, 2, 3, 4, 5};

Explanation: <int, 5> gives the type and the size.

All lessons in Beginner