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()andback()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
| Type | Size | Typical use |
|---|---|---|
| Built-in array | Fixed | Low-level interoperation or language fundamentals |
| std::array | Fixed | Fixed-size sequence with container interface |
| std::vector | Resizable | General 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
- Store seven days of temperatures in std::array and calculate their average.
- Use fill to reset all values.
- Sort an array with std::sort and begin/end.
- Explain when vector is a better choice.
Practice solutions
Show worked solutions
- Store the seven values in
std::array<double, 7>, add them in a loop, then divide the total bytemperatures.size(). Usedoubleso the average can contain a fractional part. - Call
temperatures.fill(0.0)to assign zero to every element. - Include
<algorithm>and callstd::sort(values.begin(), values.end()).std::arrayprovides random-access iterators. - Choose
std::vectorwhen the number of elements must change at runtime.std::arrayhas 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.