Learn the basics of std::array: fixed size, STL integration, and useful APIs like .size(), .at(), and .data().
std::array<T, N>is a fixed-size container (like a C array), but with a container interface..size()returnsN..at(i)checks bounds and throwsstd::out_of_rangeifiis invalid..data()returnsT*to the first element (useful to interoperate with C-style APIs)..fill(x)fills all elements withx.
File: 06_std_array.cpp
- Create
std::array<int,5> a{...}. - Show
.size()and access viaoperator[]. - Demonstrate
.at()insidetry/catch(bounds checking). - Use
.data()to show the memory is contiguous. - Call
a.fill(7)and print with range-basedfor.
- Using
operator[]expecting bounds checking (there isn’t; it’s like a C array). - Storing a pointer from
.data()and later using it incorrectly (withstd::arrayit won’t be invalidated by reallocation, but still watch lifetime/scope). - Thinking
std::arrayis “dynamic” (it isn’t; the size is part of the type).
- Write a function that takes
std::array<int, N>and returns the largest element. - Compare
a[999](UB) witha.at(999)(exception). - Convert a C array to
std::arraymanually and compare usage.
g++ -std=c++20 -O2 -Wall -Wextra -pedantic -g 06_std_array.cpp -o app
./app