┌─────────────────┬────────────────────┬─────────────────┬────────────────────────────┐
│ Container │ Memory Location │ Resizable? │ STL Algorithm Compatible? │
├─────────────────┼────────────────────┼─────────────────┼────────────────────────────┤
│ T arr[N] │ Stack / Data │ NO │ Clunky (decays to pointer) │
│ std::array │ Stack / Data │ NO │ 100% First-class STL │
│ std::vector │ Heap (Dynamic) │ YES │ 100% First-class STL │
└─────────────────┴────────────────────┴─────────────────┴────────────────────────────┘std::array in C++: Fixed-Size Arrays With STL Features
Direct Answer & Core Concept
Detailed Explanation & Mechanics
1. Comparison: C-array vs std::array vs std::vector:
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.
Runnable Code Example: std::array in C++: Fixed-Size Arrays Wit
C++20 / C++23#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;
}Common C++ Technical Interview Questions & Answers
Interview PrepQ: What is the memory overhead of `std::array` compared to `int arr[10]`?
Q: How does `std::array` prevent bugs common with C-style arrays?
Key Takeaways, Modern Best Practices & Idioms
C++ Best Practices & Production Rules
std::array over raw C-style arrays (T arr[N]) in modern C++.• 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.