Skip to main content

Lesson 4 of 7

STL Algorithms - sort, find, transform & accumulate

The `<algorithm>` header contains 100+ algorithms for searching, sorting, transforming, and reducing ranges. They work with any container via iterators, are heavily optimised, and express intent more clearly than hand-written loops. The golden rule: **prefer algorithms over raw loops**. They are harder to get wrong, have documented complexity guarantees, and are instantly recognisable to other C++ programmers.

12 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

sort, find, transform, accumulate & Functional Objects

sort, find, transform, accumulate & Functional Objects
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <numeric>
#include <functional>
#include <iterator>   // std::back_inserter, ostream_iterator

int main() {
    std::vector<int> v{5, 2, 8, 1, 9, 3, 7, 4, 6};

    // ── Sorting ────────────────────────────────────────────────
    std::sort(v.begin(), v.end());                              // ascending
    // std::sort(v.begin(), v.end(), std::greater<int>{});     // descending
    for (int n : v) std::cout << n << " ";
    std::cout << "
";   // 1 2 3 4 5 6 7 8 9

    std::stable_sort(v.begin(), v.end(), std::greater<int>{}); // stable descending

    // ── Searching ─────────────────────────────────────────────
    std::sort(v.begin(), v.end());  // re-sort ascending for binary_search
    bool found = std::binary_search(v.begin(), v.end(), 7);   // O(log n) - sorted!
    std::cout << "found 7: " << found << "
";  // 1

    auto it = std::find(v.begin(), v.end(), 5);  // O(n) linear find
    if (it != v.end()) std::cout << "find(5): pos=" << (it - v.begin()) << "
";

    auto it2 = std::find_if(v.begin(), v.end(),
                            [](int n){ return n > 6; });  // first >6
    std::cout << "first>6: " << *it2 << "
";  // 7

    // ── Transformation ────────────────────────────────────────
    std::vector<int>    src{1, 2, 3, 4, 5};
    std::vector<int>    doubled(src.size());
    std::transform(src.begin(), src.end(), doubled.begin(),
                   [](int n){ return n * 2; });
    for (int n : doubled) std::cout << n << " ";
    std::cout << "
";  // 2 4 6 8 10

    // Transform two ranges into one
    std::vector<int> sums(src.size());
    std::transform(src.begin(), src.end(), doubled.begin(), sums.begin(),
                   [](int a, int b){ return a + b; });
    for (int n : sums) std::cout << n << " ";
    std::cout << "
";  // 3 6 9 12 15

    // ── Reduction ─────────────────────────────────────────────
    int total = std::accumulate(src.begin(), src.end(), 0);  // sum
    std::cout << "sum=" << total << "
";  // 15

    int product = std::accumulate(src.begin(), src.end(), 1, std::multiplies<int>{});
    std::cout << "product=" << product << "
";   // 120

    // ── Copy, conditional copy ────────────────────────────────
    std::vector<int> evens;
    std::copy_if(src.begin(), src.end(), std::back_inserter(evens),
                 [](int n){ return n % 2 == 0; });
    for (int n : evens) std::cout << n << " ";  // 2 4
    std::cout << "
";

    // ── min_element, max_element, minmax_element ──────────────
    auto [mn, mx] = std::minmax_element(src.begin(), src.end());
    std::cout << "min=" << *mn << " max=" << *mx << "
";  // 1 5

    // ── Count, count_if ──────────────────────────────────────
    std::cout << "count(3)=" << std::count(src.begin(), src.end(), 3) << "
"; // 1
    std::cout << "count>3="  << std::count_if(src.begin(), src.end(),
                                              [](int n){ return n > 3; }) << "
"; // 2

    // ── all_of, any_of, none_of ───────────────────────────────
    std::cout << "all>0?  " << std::all_of(src.begin(),src.end(),[](int n){return n>0;}) << "
";
    std::cout << "any>4?  " << std::any_of(src.begin(),src.end(),[](int n){return n>4;}) << "
";
    std::cout << "none<0? " << std::none_of(src.begin(),src.end(),[](int n){return n<0;}) << "
";

    return 0;
}

Common Mistakes

  • `std::binary_search` requires a sorted range - calling it on an unsorted range gives wrong answers (not a crash). Always sort before binary_search/lower_bound/upper_bound.
  • `std::transform` requires the output range to have already allocated space - `std::transform` does NOT grow the destination. If `dest` is empty, you write to `dest.begin()` == `dest.end()` - undefined behaviour. Either pre-size with `dst.resize(n)` or use `std::back_inserter(dst)` to auto-grow.
  • `std::remove`/`std::remove_if` doesn't actually erase - it shuffles matching elements to the end and returns an iterator to the new end. You must call `v.erase(remove_if(...), v.end())` - the erase-remove idiom - to actually shrink the container.

Tip

Tip

Practice STL Algorithms sort find transform accumulate in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

High-performance iterator-based algorithms and custom lambda predicates

Practice Task

Note

Practice Task - (1) Write a working example of STL Algorithms sort find transform accumulate from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with STL Algorithms sort find transform accumulate is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.

Key Takeaways

  • The `<algorithm>` header contains 100+ algorithms for searching, sorting, transforming, and reducing ranges.
  • `std::binary_search` requires a sorted range - calling it on an unsorted range gives wrong answers (not a crash). Always sort before binary_search/lower_bound/upper_bound.
  • `std::transform` requires the output range to have already allocated space - `std::transform` does NOT grow the destination. If `dest` is empty, you write to `dest.begin()` == `dest.end()` - undefined behaviour. Either pre-size with `dst.resize(n)` or use `std::back_inserter(dst)` to auto-grow.
  • `std::remove`/`std::remove_if` doesn't actually erase - it shuffles matching elements to the end and returns an iterator to the new end. You must call `v.erase(remove_if(...), v.end())` - the erase-remove idiom - to actually shrink the container.

Topics in This Module

0/7 done