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
| idx | value |
|---|---|
| 0-2 | kept |
| 3-4 | garbage |
| size | unchanged |
after erase
| idx | value |
|---|---|
| 0-2 | kept |
| — | removed |
| size | shrunk |
3
Iterator Categories
What an algorithm can demand of your container.
Complexity
| input / output | single pass | streams |
| forward | multi-pass | forward_list |
| bidirectional | ++ and -- | list, map |
| random access | it + 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.