Table of Contents

<algorithm>

<algorithm> provides a library of generic algorithms that operate on ranges of elements: searching, sorting, transforming, and counting. These functions work with any container that provides iterators (vectors, lists, arrays), and they follow a consistent prefix convention for variants (_if, _n).

The most commonly used are std::sort, std::find, std::copy, and range queries like std::all_of, std::any_of. Many algorithms have been extended in C++20 to work directly with ranges without explicit iterator pairs.

Example

This example sorts a vector of integers, searches for an element, and counts how many meet a condition using predicates.

// compile: g++ -std=c++20 -o algo algo.cpp
// run: ./algo
// description: sort integers, find an element, and count matching elements
 
#include <algorithm>
#include <iostream>
#include <vector>
 
int main() {
    std::vector<int> nums = {5, 2, 8, 1, 9, 3};
 
    std::sort(nums.begin(), nums.end());
 
    auto it = std::find(nums.begin(), nums.end(), 5);
    if (it != nums.end()) {
        std::cout << "found 5 at position " << std::distance(nums.begin(), it) << "\n";
    }
 
    int count = std::count_if(nums.begin(), nums.end(), 
                              [](int x) { return x > 3; });
    std::cout << "elements > 3: " << count << "\n";
 
    return 0;
}