thecodex.expert · The Codex Family of Knowledge
C++

STL Algorithms

A hand-written loop for something like std::sort or std::find is genuinely more likely to have an off-by-one bug than the standard library’s own tested, optimized implementation — that’s the real case for using them.

C++20 / C++23 Prefer over hand-written loops Last verified:
Canonical Definition

Algorithms like std::sort, std::find, and std::transform take a pair of iterators (begin/end) marking a range, making them work identically across any container that provides compatible iterators — the same std::sort call works on a vector, a deque, or a plain array. Beyond genericity, using a standard algorithm instead of a hand-written loop is typically both safer (the standard library's implementation has been extensively tested) and more self-documenting (std::find_if immediately communicates intent, where an equivalent hand-rolled loop requires reading the whole body to understand).

sort and find: the essentials

The comparator lambda passed to sort controls the ordering directly, without needing a separate named comparison function for a one-off case.

C++sort_find.cpp
std::vector<int> v = {5, 2, 8, 1, 9};

std::sort(v.begin(), v.end());                     // ascending: 1 2 5 8 9
std::sort(v.begin(), v.end(), std::greater<>());   // descending: 9 8 5 2 1

auto it = std::find(v.begin(), v.end(), 8);
if (it != v.end()) {
    std::cout << "found at index " << (it - v.begin()) << "\n";
}

transform and accumulate: functional-style operations

transform applies a function to every element, writing results to a destination; accumulate folds a range down to a single value — both replace what would otherwise be a manual loop with explicit indexing.

C++transform_accumulate.cpp
std::vector<int> nums = {1, 2, 3, 4};
std::vector<int> doubled(nums.size());

std::transform(nums.begin(), nums.end(), doubled.begin(),
    [](int n) { return n * 2; });   // doubled: 2 4 6 8

int sum = std::accumulate(nums.begin(), nums.end(), 0);   // 10 — folds the range to one value

find_if: searching by a condition, not an exact value

Unlike find (which needs an exact value to match), find_if takes a predicate — any lambda returning bool — letting the search condition be arbitrarily complex while the call itself stays readable.

C++find_if_example.cpp
std::vector<int> v = {3, 7, 12, 5, 20};

auto it = std::find_if(v.begin(), v.end(), [](int n) {
    return n > 10;   // find the first element satisfying an arbitrary condition
});

if (it != v.end()) {
    std::cout << "first value over 10: " << *it << "\n";   // 12
}

Sources

1
ISO/IEC 14882 (C++ Standard), "Algorithms library," cppreference.com/w/cpp/algorithm.