Lesson 23 of 25

STL Algorithms

Common Algorithms

The STL algorithms library provides functions for sorting, searching, transforming, and more.

Example
#include <algorithm>
#include <numeric>
#include <vector>
using namespace std;

vector<int> nums = {5, 3, 1, 4, 2};

// Sort
sort(nums.begin(), nums.end());        // {1, 2, 3, 4, 5}
sort(nums.begin(), nums.end(), greater<>()); // descending

// Find
auto it = find(nums.begin(), nums.end(), 3);
if (it != nums.end()) cout << "Found: " << *it << endl;

// Min/Max
auto [mn, mx] = minmax_element(nums.begin(), nums.end());
cout << *mn << " " << *mx << endl;

// Count and accumulate
int count = count_if(nums.begin(), nums.end(), [](int n){ return n > 3; });
int sum = accumulate(nums.begin(), nums.end(), 0);

// Transform
vector<int> doubled(nums.size());
transform(nums.begin(), nums.end(), doubled.begin(),
    [](int n){ return n * 2; });

// Remove-erase idiom
nums.erase(remove_if(nums.begin(), nums.end(),
    [](int n){ return n < 3; }), nums.end());