STL Algorithms
Standard algorithms for everyday programming
Non-modifying Algorithms
#include <algorithm>
#include <vector>
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// Find elements
auto it = std::find(v.begin(), v.end(), 5);
auto it2 = std::find_if(v.begin(), v.end(),
[](int x) { return x > 5; });
// Check conditions
bool has_even = std::any_of(v.begin(), v.end(),
[](int x) { return x % 2 == 0; });
bool all_positive = std::all_of(v.begin(), v.end(),
[](int x) { return x > 0; });
// Count
int count = std::count(v.begin(), v.end(), 5);
int evens = std::count_if(v.begin(), v.end(),
[](int x) { return x % 2 == 0; });
// Search
bool found = std::binary_search(v.begin(), v.end(), 5); // O(log n)Modifying Algorithms
std::vector<int> v = {1, 2, 3, 4, 5};
// Transform
std::vector<int> squared;
std::transform(v.begin(), v.end(), std::back_inserter(squared),
[](int x) { return x * x; });
// Copy with condition
std::vector<int> evens;
std::copy_if(v.begin(), v.end(), std::back_inserter(evens),
[](int x) { return x % 2 == 0; });
// Remove (returns new end, doesn't shrink)
auto new_end = std::remove(v.begin(), v.end(), 3);
v.erase(new_end, v.end()); // Actually remove
// Remove while copying
std::vector<int> no_fives;
std::remove_copy_if(v.begin(), v.end(), std::back_inserter(no_fives),
[](int x) { return x == 5; });
// Replace
std::replace(v.begin(), v.end(), 2, 99); // Replace all 2s with 99
// Fill/Generate
std::fill(v.begin(), v.end(), 0);
std::iota(v.begin(), v.end(), 1); // 1, 2, 3, 4, 5...Sorting and Related
std::vector<int> v = {3, 1, 4, 1, 5, 9, 2, 6};
// Sort
std::sort(v.begin(), v.end()); // O(n log n)
std::sort(v.begin(), v.end(), std::greater<>()); // Descending
// Stable sort (preserves order of equal elements)
std::stable_sort(v.begin(), v.end());
// Partial sort - only need top k
std::partial_sort(v.begin(), v.begin() + 3, v.end());
// Now first 3 elements are the 3 smallest, in order
// Nth element - quickselect
std::nth_element(v.begin(), v.begin() + 4, v.end());
// Element at position 4 is what it would be if sorted
// Binary search (requires sorted range)
bool exists = std::binary_search(v.begin(), v.end(), 5);
auto lower = std::lower_bound(v.begin(), v.end(), 5); // First >= 5
auto upper = std::upper_bound(v.begin(), v.end(), 5); // First > 5C++20 Ranges Algorithms
#include <ranges>
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// Ranges versions - work with views!
auto result = std::ranges::find(v, 5);
auto evens = std::ranges::count_if(v,
[](int x) { return x % 2 == 0; });
// Projections - transform before comparing
struct Person { std::string name; int age; };
std::vector<Person> people = {{"Alice", 30}, {"Bob", 25}};
// Sort by age using projection
std::ranges::sort(people, {}, &Person::age);
// Find by name projection
auto it = std::ranges::find(people, "Alice", &Person::name);
// Sort + projection in one line
std::ranges::sort(people, std::ranges::greater{}, &Person::age);