ReviseAlgo Logo

Standard Template Library (STL)

STL Algorithms

Generic algorithms that operate on ranges via iterators — sort, find, transform, and more

Interview: STL fluency is expected — using algorithms instead of raw loops signals C++ expertise

STL Algorithms

STL algorithms in <algorithm> operate on iterator ranges, decoupling the algorithm from the container. They are type-safe, well-tested, and often more efficient than hand-written loops. Using them instead of raw loops communicates intent clearly and eliminates off-by-one errors.

Most Important Algorithms

Sorting

sort O(n log n), stable_sort preserves order of equal elements, partial_sort for top-K.

Searching

find, find_if, binary_search, lower_bound, upper_bound.

Transformation

transform, for_each, fill, generate, replace_if.

Reduction

accumulate, reduce (C++17, parallelizable), count, count_if, min_element, max_element.

Partitioning

partition, stable_partition, remove_if + erase idiom.

Set Operations

set_union, set_intersection, set_difference on sorted ranges.

Interview Corner

Q: What is the erase-remove idiom and why do you need both erase and remove?

A: std::remove_if doesn't actually erase elements — it moves matching elements to the end and returns an iterator to the new logical end. The elements past that iterator are in a valid but unspecified state. erase then physically removes them. Combined: v.erase(std::remove_if(v.begin(), v.end(), pred), v.end()); — O(n) time, single pass.

Common Pitfalls

  • Using remove_if without erase: remove_if alone doesn't shrink the container — the elements appear gone but still occupy memory.
  • Using binary_search to find position: binary_search returns bool, not an iterator. Use lower_bound to get the position of an element.

Best Practices

  • Prefer STL algorithms over manual loops — they communicate intent, are tested, and often more optimizable by the compiler.
  • Use lambdas with algorithms for readable, inline predicates: sort(v.begin(), v.end(), [](int a, int b){ return a > b; });