Skip to content
AgileLogics
5 min read

STL Algorithms

Prerequisites: Iterators

<algorithm> provides ready-made, well-tested implementations of common operations, working through iterators rather than being tied to one container:

#include <algorithm>
#include <vector>

std::vector<int> nums = {5, 3, 8, 1, 9};

std::sort(nums.begin(), nums.end());
// nums is now {1, 3, 5, 8, 9}

bool hasEight = std::find(nums.begin(), nums.end(), 8) != nums.end();

int count = std::count_if(nums.begin(), nums.end(),
    [](int n) { return n > 3; }); // 3 — lambda, covered shortly

Reaching for std::sort/std::find/std::count_if instead of hand-writing the equivalent loop (as you did in C) is both less code and, in most cases, at least as fast — the standard library's implementations are heavily optimized and battle-tested.