C++ PROGRAMMING ยท 12 MIN STUDY

Fixed-size sequences with std::array

Use std::array for fixed-size collections with standard container operations.

Learning objectives

  • Explain when a fixed-size array is appropriate.
  • Create and initialize std::array.
  • Use size, at, front, back, and range-based loops.
  • Compare std::array with built-in arrays and vector.

Prerequisites: understand fixed-size C-style arrays, indexing, and basic loops. Review Arrays if needed.

What is std::array?

std::array<T, N> is a standard-library container that stores exactly N elements of type T. Its size is part of the type and does not change at runtime. Unlike a built-in array, it provides standard container member functions and works naturally with algorithms.

C++17
#include <array>
#include <iostream>

int main() {
    std::array<int, 4> marks{80, 92, 75, 88};
    for (int mark : marks) {
        std::cout << mark << '\n';
    }
}

Access and inspect

  • size() returns the number of elements.
  • at(i) checks bounds and throws on invalid access.
  • [i] accesses an element without bounds checking.
  • front() and back() access the first and last elements when the array is not empty.
  • fill(value) assigns the same value to every element.

Choose the right container

TypeSizeTypical use
Built-in arrayFixedLow-level interoperation or language fundamentals
std::arrayFixedFixed-size sequence with container interface
std::vectorResizableGeneral dynamic sequence

Common mistakes

  • Expecting std::array to grow with push_back.
  • Using an invalid index with operator[].
  • Calling front or back when the array is empty (possible for N = 0).
  • Confusing the template size parameter with the current number of elements.

Practice

  1. Store seven days of temperatures in std::array and calculate their average.
  2. Use fill to reset all values.
  3. Sort an array with std::sort and begin/end.
  4. Explain when vector is a better choice.

Practice solutions

Show worked solutions
  1. Store the seven values in std::array<double, 7>, add them in a loop, then divide the total by temperatures.size(). Use double so the average can contain a fractional part.
  2. Call temperatures.fill(0.0) to assign zero to every element.
  3. Include <algorithm> and call std::sort(values.begin(), values.end()). std::array provides random-access iterators.
  4. Choose std::vector when the number of elements must change at runtime. std::array has a fixed size that is part of its type.

Check your understanding

Can std::array change its size at runtime?

Answer: No. Its size N is part of its type and is fixed.

Summary

Use std::array for fixed-size sequences that benefit from standard container operations. Use vector when the number of elements needs to change.

References