cpp / intermediate
Snippet
Fixed-Size Standard Library Arrays
The std::array container provides the performance of a raw C-style array with the interface benefits of standard containers. It knows its own size and supports iterators, making it compatible with range-based loops and standard algorithms without the risk of pointer decay.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>#include <array>int main() {// std::array is a thin wrapper around C-style arraysstd::array<int, 3> coordinates = {10, 20, 30};std::cout << "Array size: " << coordinates.size() << std::endl;for (int val : coordinates) {std::cout << "Coord: " << val << std::endl;}return 0;}
Breakdown
1
std::array<int, 3> coordinates
Defines a fixed-size array of 3 integers at compile time.
2
coordinates.size()
Returns the number of elements, unlike sizeof() on pointers which returns byte size.