0 day streak
cpp / intermediate
Snippet

Safe Boundary Validation in Collections

While the subscript operator [] is fast, it does not perform any bounds checking, leading to undefined behavior on invalid indices. The at() method provided by standard containers validates the index and throws a std::out_of_range exception if the access is invalid, prioritizing safety over raw speed.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <array>
#include <stdexcept>
int main() {
std::array<int, 3> coords = {10, 20, 30};
try {
// at() performs bounds checking
int val = coords.at(5);
std::cout << "Value: " << val << "\n";
} catch (const std::out_of_range& e) {
std::cerr << "Error: Access out of bounds! " << e.what() << "\n";
}
return 0;
}
Breakdown
1
int val = coords.at(5);
Attempts to access index 5; throws an exception since the array size is only 3.
2
catch (const std::out_of_range& e)
Catches the specific exception type thrown by the at() method.