11.2 — The algorithm toolbox

📘 Chapter 11⏱ about 1 min read✍️ Beginner friendly
Read one box at a time. No rush.

Don't write it yourself#

The <algorithm> library has dozens of ready-made tools for lists. They're tested, fast, and save you writing loops.

C++
#include <algorithm>#include <vector> std::vector<int> v { 5, 2, 8, 2, 9 };

The most useful ones#

CodeWhat it does
std::sort(v.begin(), v.end())sort small → big
std::reverse(v.begin(), v.end())flip the order
std::find(v.begin(), v.end(), 8)find the first 8
std::count(v.begin(), v.end(), 2)how many 2s (here: 2)
std::max_element(v.begin(), v.end())the biggest item
std::min(a, b) / std::max(a, b)smaller / bigger of two

Using find#

find gives back an iterator — a position marker. If it equals v.end(), nothing was found:

C++
auto it { std::find(v.begin(), v.end(), 8) };if (it != v.end()){    std::cout << "Found 8!\n";}

Lambdas: tiny functions on the spot#

Some tools take a small function to decide things. Write it right there with a lambda:

C++
// sort big → smallstd::sort(v.begin(), v.end(), [](int a, int b) { return a > b; }); // count the even numbersauto evens { std::count_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; }) };

[](int x) { ... } is a function with no name. The [] starts it.

Ranges (C++20)

Newer C++ lets you skip begin()/end(): std::ranges::sort(v); does the same as std::sort(v.begin(), v.end());.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.