Skip to content
C++

STL Algorithms

Common algorithm functions.

By EZ4Code Team
algorithmalgorithm

Code

#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <string>

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

    // Sort
    std::sort(v.begin(), v.end());
    // Descending order
    std::sort(v.begin(), v.end(), std::greater<int>());

    // Find
    auto it = std::find(v.begin(), v.end(), 5);
    bool exists = std::count(v.begin(), v.end(), 1) > 0;

    // Transform
    std::vector<int> doubled;
    std::transform(v.begin(), v.end(), std::back_inserter(doubled),
        [](int x) { return x * 2; });

    // Filter
    std::vector<int> evens;
    std::copy_if(v.begin(), v.end(), std::back_inserter(evens),
        [](int x) { return x % 2 == 0; });

    // Aggregate
    int sum = std::accumulate(v.begin(), v.end(), 0);
    int product = std::accumulate(v.begin(), v.end(), 1, std::multiplies<>());

    // min/max
    auto [minit, maxit] = std::minmax_element(v.begin(), v.end());

    // Deduplicate (requires sorting first)
    std::sort(v.begin(), v.end());
    v.erase(std::unique(v.begin(), v.end()), v.end());

    std::cout << "sum=" << sum << " min=" << *minit
              << " max=" << *maxit << "\n";
    return 0;
}

Explanation

STL algorithms work with iterators; sort, find, transform, accumulate for sorting, finding, transforming, aggregating.

More C++ Snippets