Lesson 18 • Advanced
STL Algorithm Mastery
Master the STL algorithm library: sort, find, transform, accumulate, partition, and the remove-erase idiom.
What You'll Learn
- ✓ Sorting with custom comparators
- ✓ find, find_if, count_if, binary_search
- ✓ transform and accumulate for data processing
- ✓ partition, remove-erase, and unique
Why Use STL Algorithms?
Writing your own loops is fine for simple tasks, but STL algorithms are battle-tested, optimised, and self-documenting. When you see sort(), you know exactly what happens. When you see a 15-line loop, you have to read every line.
STL algorithms operate on iterator ranges — a pair of begin() and end() iterators. This means the same algorithm works with vectors, arrays, deques, and any container that provides iterators.
Sort, Find & Search
Sort with custom comparators and search with find_if and binary_search
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> nums = {42, 17, 8, 95, 23, 61, 3, 77};
// sort — default ascending
sort(nums.begin(), nums.end());
cout << "Sorted: ";
for (int n : nums) cout << n << " ";
cout << endl;
// sort descending with comparator
sort(nums.begin(), nums.end(), greater<int>());
cout << "Descending: ";
for (int n : nums) cout << n << " ";
cout << endl;
//
...Transform & Accumulate
Process data with transform, accumulate, min/max, and for_each
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
int main() {
vector<int> prices = {1299, 2499, 599, 3999, 899};
// transform — apply function to each element
cout << "=== transform ===" << endl;
vector<double> dollars(prices.size());
transform(prices.begin(), prices.end(), dollars.begin(),
[](int cents) { return cents / 100.0; });
cout << "Prices in dollars: ";
for (double d : dollars) cout << "$" <
...Partition, Remove & Unique
Rearrange, filter, and deduplicate elements efficiently
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void printVec(const string& label, const vector<int>& v) {
cout << label << ": ";
for (int n : v) cout << n << " ";
cout << endl;
}
int main() {
// partition — rearrange so predicate-true elements come first
cout << "=== partition ===" << endl;
vector<int> nums = {1, 8, 3, 6, 2, 9, 4, 7, 5};
auto pivotIt = partition(nums.begin(), nums.end(), [](int n) {
return n % 2 == 0; /
...Common Mistakes
⚠️ binary_search on unsorted data: binary_search requires a sorted range. On unsorted data, results are undefined.
⚠️ Forgetting erase after remove: remove() doesn't shrink the container — it returns the new logical end. You must call erase() to actually remove elements.
⚠️ Invalidating iterators: Modifying a container while iterating with algorithms can invalidate iterators. Use the remove-erase idiom instead.
Pro Tips
💡 Use ranges (C++20): ranges::sort(vec) is cleaner than sort(vec.begin(), vec.end()).
💡 nth_element for partial sorts: If you only need the top-N elements, nth_element is O(n) instead of O(n log n).
💡 Combine algorithms: Chain sort → unique → erase for a fast deduplicate, or partition → process each half separately.
📋 Quick Reference
| Algorithm | Purpose | Complexity |
|---|---|---|
sort | Sort range | O(n log n) |
find / find_if | Linear search | O(n) |
binary_search | Sorted search | O(log n) |
transform | Apply function | O(n) |
accumulate | Reduce/fold | O(n) |
partition | Split by predicate | O(n) |
Lesson Complete!
You now command the most important STL algorithms for sorting, searching, transforming, and filtering data. Next: Advanced Containers — internals of vector, list, map, unordered_map, and deque.
Sign up for free to track which lessons you've completed and get learning reminders.