0 day streak
cpp / intermediate
Snippet

Stack-Allocated Fixed-Size Containers

The std::array container provides the performance of raw C-style arrays but with the safety of a container. Unlike raw arrays, it does not decay to a pointer and supports bounds checking via the .at() method.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <array>
void processBuffer() {
std::array<int, 5> data = {10, 20, 30, 40, 50};
try {
int val = data.at(2);
std::cout << "Value: " << val << std::endl;
} catch (const std::out_of_range& e) {
std::cerr << "Access error: " << e.what() << std::endl;
}
}
Breakdown
1
std::array<int, 5> data = {10, 20, 30, 40, 50};
Defines a fixed-size array of 5 integers directly on the stack.
2
data.at(2);
Accesses the third element with bounds checking, throwing an exception if the index is invalid.