0 day streak
cpp / intermediate
Snippet

Modern Containerized Arrays

Unlike raw C-style arrays, std::array is a container that knows its own size and doesn't decay into a pointer automatically. It provides a more robust way to handle fixed-size collections while maintaining zero-overhead performance compared to traditional arrays.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <array>
int main() {
// std::array provides a safer alternative to C-style arrays
std::array<int, 4> scores = {85, 92, 78, 90};
// Size information is built-in and accessible
for(std::size_t i = 0; i < scores.size(); ++i) {
std::cout << "Score " << i << ": " << scores[i] << std::endl;
}
return 0;
}
Breakdown
1
std::array<int, 4> scores = {85, 92, 78, 90};
Declares a fixed-size array container for 4 integers.
2
scores.size()
Accesses the built-in size member, avoiding the need for manual tracking.