0 day streak
cpp / intermediate
Snippet

Compile-Time Sized Containers

std::array is a thin wrapper around C-style arrays that provides the benefits of standard containers (like iterators and size queries) without any runtime overhead. It is the preferred choice for fixed-size collections in modern C++.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <array>
#include <algorithm>
int main() {
// std::array knows its size and doesn't decay to a pointer easily
std::array<int, 5> numbers = {5, 2, 8, 1, 9};
std::sort(numbers.begin(), numbers.end());
for (const auto& num : numbers) {
std::cout << num << " ";
}
return 0;
}
Breakdown
1
std::array<int, 5> numbers = {5, 2, 8, 1, 9};
Defines an array of 5 integers. The size is part of the type definition.