C++C++ Explainer
C++ · 5 · STL22 / 36 · 61%

Algorithms & Iterators

Stop writing raw loops — the library already has the loop, tested and optimized.

Examples: sort, find_if, accumulate, transform

shortcuts: ← prev · → next · M mark
1

The Core Set

Most loops you write are one of these.

Example
example
#include <algorithm>
#include <numeric>

std::sort(v.begin(), v.end());
auto it  = std::find_if(v.begin(), v.end(), [](int x){ return x > 10; });
int  sum = std::accumulate(v.begin(), v.end(), 0);
std::transform(v.begin(), v.end(), out.begin(), [](int x){ return x * 2; });
bool any = std::any_of(v.begin(), v.end(), is_valid);
2

The Erase-Remove Idiom

remove only shuffles elements; erase actually shrinks the container.

Example
example
// pre-C++20
v.erase(std::remove(v.begin(), v.end(), 42), v.end());

// C++20
std::erase(v, 42);
std::erase_if(v, [](int x){ return x % 2 == 0; });
after std::remove
idxvalue
0-2kept
3-4garbage
sizeunchanged
→
after erase
idxvalue
0-2kept
—removed
sizeshrunk
3

Iterator Categories

What an algorithm can demand of your container.

Complexity
input / outputsingle passstreams
forwardmulti-passforward_list
bidirectional++ and --list, map
random accessit + n in O(1)vector, deque, array
TIP
std::sort needs random access — that's why you call list::sort() for a std::list.
4

Invalidation

Mutating a container while iterating is the classic crash.

Common pitfalls
  • ✕vector: any push_back may reallocate and invalidate every iterator, pointer and reference.
  • ✕vector erase invalidates everything from the erase point onward.
  • ✕map/set: erase invalidates only the erased iterator; use it = m.erase(it).
  • ✕Never keep an iterator across a resize.