Modern C++ • C++20 baseline
Built-In Arrays, std::array, and std::vector
Choose a container that communicates whether size is fixed or changes at runtime.
Built-in arrays are useful at low-level boundaries but do not carry their length when passed as pointers. std::array owns a fixed number of elements and exposes its size. std::vector owns a dynamically sized contiguous sequence; its capacity can change, so some operations invalidate pointers, references, and iterators.
Key points
- Prefer standard containers over manually allocated arrays.
- Use at() when checked indexing is more valuable than unchecked access.
Example
#include <array>
#include <iostream>
#include <vector>
int main() {
const std::array<int, 3> fixed{2, 4, 6};
std::vector<int> growing(fixed.begin(), fixed.end());
growing.push_back(8);
std::cout << fixed.size() << ' ' << growing.size() << '\n';
}
What to expect
3 4
Practice exercise
Store a set of temperatures in a vector and compute its minimum with a standard algorithm.
Key idea: Containers manage storage and expose useful invariants; select them before reaching for raw allocation.