std::array in C++: Fixed-Size Arrays With STL Features
What is std::array in C++: Fixed-Size Arrays With STL Features? std::array is a sequence container that encapsulates a fixed-size stack-allocated array. It combines the zero-overhead memory layout of C-style arrays with the...
What is std::array in C++11, how does it compare to raw C-style arrays and std::vector, and what are its performance advantages?
Explanation & In-Depth Details
```text
┌─────────────────┬────────────────────┬─────────────────┬────────────────────────────┐
│ Container │ Memory Location │ Resizable? │ STL Algorithm Compatible? │
├─────────────────┼────────────────────┼─────────────────┼────────────────────────────┤
│ T arr[N] │ Stack / Data │ NO │ Clunky (decays to pointer) │
│ std::array<T,N> │ Stack / Data │ NO │ 100% First-class STL │
│ std::vector<T> │ Heap (Dynamic) │ YES │ 100% First-class STL │
└─────────────────┴────────────────────┴─────────────────┴────────────────────────────┘
```
2. No Pointer Decay:
Unlike raw C-arrays, `std::array` does not implicitly decay to a raw pointer when passed to functions; it preserves its size and type information.
Code Example
#include <iostream>
#include <array>
#include <algorithm>
void printArray(const std::array<int, 5>& arr) {
std::cout << "Array elements (" << arr.size() << " items): ";
for (int val : arr) std::cout << val << " ";
std::cout << "\n";
}
int main() {
// Fixed size stack allocation: std::array<Type, Size>
std::array<int, 5> numbers = {50, 20, 10, 40, 30};
// Full STL Algorithm support
std::sort(numbers.begin(), numbers.end());
printArray(numbers);
// Bounds checked access
std::cout << "Element at index 2: " << numbers.at(2) << "\n";
std::cout << "Front: " << numbers.front() << ", Back: " << numbers.back() << "\n";
return 0;
}Interview Question & Tips
A: Exactly zero. `sizeof(std::array<int, 10>) == sizeof(int[10]) == 40 bytes`. It has no extra heap allocations or pointer members.
Q: How does `std::array` prevent bugs common with C-style arrays?
A: It eliminates implicit pointer decay, tracks its own `.size()`, supports standard copy/assignment operators (`arr1 = arr2;`), and provides bounds checking with `.at()`.
Best Practices
• Use `std::array` when container size is fixed at compile time to avoid dynamic heap allocation costs of `std::vector`.
• Use `.at(index)` when checking array bounds is necessary to prevent buffer overflows.
This study reference for std::array in C++: Fixed-Size Arrays With STL Features is curated and verified against recognized curriculum benchmarks, peer-reviewed textbooks, and official technical documentation: