STL Containers
STL Containers
When to use vectors, arrays, maps, sets, queues, and container adapters.
STL Containers
When to use vectors, arrays, maps, sets, queues, and container adapters.
std::array<T, N>: fixed-size wrapper over stack-style storagestd::vector<T>: dynamic contiguous storage, default first choicestd::deque<T>: efficient push/pop at both endsstd::list<T>: linked list, rarely the best optionstd::forward_list<T>: singly linked liststd::set<T> / std::multiset<T>std::map<K, V> / std::multimap<K, V>Tree-based and ordered by key.
std::unordered_set<T>std::unordered_map<K, V>Hash-based with average constant-time lookup.
std::stack<T>std::queue<T>std::priority_queue<T>std::vector<int> values{1, 2, 3};
values.push_back(4);
values.emplace_back(5);
values.erase(values.begin());
for (auto it = values.begin(); it != values.end(); ++it) {
std::cout << *it << '\n';
}
std::vectorstd::array when size is fixed at compile timestd::unordered_map for fast key lookup when ordering is irrelevantstd::vector: insert/erase may invalidate iterators and references after the changed position; reallocation invalidates all of them.std::deque: middle insert/erase can invalidate many iterators.std::list and std::forward_list: iterators stay valid except for erased elements.void render(std::span<const int> pixels);
std::mdspan<float, std::extents<std::size_t, 4, 4>> matrix(view_ptr);
std::span gives a lightweight view over contiguous data.std::mdspan is a C++23 multidimensional non-owning view.emplace_back when constructing elements directly in place.reserve() when you know approximate vector growth.flat_map style containers only through external libraries when profiling justifies them.