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

Start with std::vector

std::vector<int> values{5, 2, 8, 1};
std::sort(values.begin(), values.end());

Find and count

auto it = std::find(values.begin(), values.end(), 8);
auto zeros = std::count(values.begin(), values.end(), 0);

Transform

std::vector<int> doubled(values.size());
std::transform(values.begin(), values.end(), doubled.begin(),
               [](int x) { return x * 2; });

Main lesson

Think in terms of operations on a range, not always in terms of manual index loops.

The erase-remove pattern

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.

Modern ranges form

std::ranges::sort(values);
auto found = std::ranges::find(values, 8);

The ranges overloads are easier to read because they work directly with containers.

Projection example

When sorting objects, you can project on a member instead of writing a custom comparator for every case.