SyntaxStudy
Sign Up
C++ STL Algorithms and Iterators
C++ Beginner 1 min read

STL Algorithms and Iterators

The '' header provides over a hundred generic algorithms that operate on iterator ranges rather than specific container types. This separation of containers from algorithms through iterators is one of the STL's most powerful design decisions — the same 'std::sort' works on vectors, arrays, and deques. Algorithms come in categories: sorting, searching, modifying, partitioning, and numeric operations. Iterators are objects that generalise pointers, abstracting over the traversal mechanism of a container. The iterator category hierarchy — from input/output through forward, bidirectional, to random-access — determines which algorithms can be applied. Random-access iterators support arithmetic ('it + n', 'it1 - it2'), while bidirectional iterators support only '++' and '--'. C++20 introduced ranges, which integrate algorithms and views into a composable pipeline with lazy evaluation. Range views such as 'std::views::filter' and 'std::views::transform' create lightweight adaptor objects that evaluate elements on demand. Pipelines written with the pipe operator '|' are readable and avoid creating intermediate containers.
Example
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <functional>
#include <iterator>

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

    // Sorting
    std::sort(nums.begin(), nums.end());
    std::cout << "sorted:   ";
    std::copy(nums.begin(), nums.end(),
              std::ostream_iterator<int>(std::cout, " "));
    std::cout << "\n";

    // Binary search on sorted range
    std::cout << "has 7: "
              << std::binary_search(nums.begin(), nums.end(), 7) << "\n";

    // Partition: evens first
    std::vector<int> v2 = {1,2,3,4,5,6,7,8};
    auto mid = std::partition(v2.begin(), v2.end(),
                              [](int n){ return n % 2 == 0; });
    std::cout << "evens: ";
    for (auto it = v2.begin(); it != mid; ++it)
        std::cout << *it << " ";
    std::cout << "\n";

    // Transform: square each element
    std::vector<int> squares(nums.size());
    std::transform(nums.begin(), nums.end(), squares.begin(),
                   [](int n){ return n * n; });
    std::cout << "squares: ";
    for (int x : squares) std::cout << x << " ";
    std::cout << "\n";

    // Numeric accumulate
    int total = std::accumulate(nums.begin(), nums.end(), 0);
    std::cout << "sum = " << total << "\n";

    // Min/max element
    auto [lo, hi] = std::minmax_element(nums.begin(), nums.end());
    std::cout << "min=" << *lo << " max=" << *hi << "\n";

    return 0;
}