STL Containers and Algorithms
STL Containers and Algorithms
Combine containers, iterators, and algorithms to write expressive code with less manual looping.
STL Containers and Algorithms
Combine containers, iterators, and algorithms to write expressive code with less manual looping.
std::vectorstd::vector<int> values{5, 2, 8, 1};
std::sort(values.begin(), values.end());
auto it = std::find(values.begin(), values.end(), 8);
auto zeros = std::count(values.begin(), values.end(), 0);
std::vector<int> doubled(values.size());
std::transform(values.begin(), values.end(), doubled.begin(),
[](int x) { return x * 2; });
Think in terms of operations on a range, not always in terms of manual index loops.
values.erase(std::remove(values.begin(), values.end(), 0), values.end());
Older STL algorithms often rearrange elements but do not actually shrink the container. Learn this pattern early.
std::ranges::sort(values);
auto found = std::ranges::find(values, 8);
The ranges overloads are easier to read because they work directly with containers.
When sorting objects, you can project on a member instead of writing a custom comparator for every case.