Core Algorithms: find, count, sort, and Friends
intermediate25 min readLesson 98 of 204
The everyday <algorithm> vocabulary, the end() check habit, _if predicates, and honest complexity.
The <algorithm> header is a vocabulary of loops other people have already
written โ tested, named, and complexity-documented. Reading code that uses
it is faster than reading hand-rolled loops.
#include <algorithm>
#include <vector>
std::vector<int> v{4, 1, 3, 1, 5};
auto it = std::find(v.begin(), v.end(), 3); // iterator or end()
int n = std::count(v.begin(), v.end(), 1); // how many 1s
bool has = std::any_of(v.begin(), v.end(),
[](int x) { return x > 4; });
std::sort(v.begin(), v.end()); // O(n log n), ascending
std::reverse(v.begin(), v.end());
auto mx = *std::max_element(v.begin(), v.end());
Three habits that make algorithms safe:
- Check before dereferencing.
std::findreturnsend()when nothing matches; comparing againstend()is the only safe move. - Prefer the
_iffamily with a predicate instead of transforming data to fit a non-_ifversion. - Read the complexity line.
sortis O(n log n);countis O(n); nothing here is free.