C++ ยท Chapter 45 of 49

C++ STL Algorithms

The `<algorithm>` header provides ready-made functions like `sort()`, `reverse()`, `find()`, and `binary_search()` that operate on ranges defined by iterators, usually a container's `.begin()` and `.end()`.

Using these battle-tested algorithms is usually faster and less error-prone than hand-writing loops, and they work uniformly across vectors, arrays, and other containers.

Sorting

`std::sort(v.begin(), v.end());` sorts a vector in ascending order in-place. Pass a custom comparator function to sort by a different order, like descending.

Searching

`std::find(v.begin(), v.end(), value)` returns an iterator to the first match, or `v.end()` if not found. `binary_search` requires a sorted range and returns a bool.

Example 1 (cpp)
#include <algorithm>
#include <vector>
std::vector<int> v = {3, 1, 2};
std::sort(v.begin(), v.end());
for (int x : v) std::cout << x;
Output
123

sort() rearranges the vector into ascending order in-place.

Example 2 (cpp)
std::vector<int> v = {1,2,3};
auto it = std::find(v.begin(), v.end(), 2);
std::cout << (it != v.end());
Output
1

find() returns an iterator; comparing to end() tells you if it was found.

Key points

  • <algorithm> provides sort, reverse, find, binary_search and more.
  • Algorithms operate on iterator ranges like begin()/end().
  • sort() modifies the container in-place, ascending by default.
  • binary_search requires the range to already be sorted.
๐Ÿ’ก Note: Passing a lambda as a comparator to sort() (e.g. `[](int a,int b){return a>b;}`) is a quick way to sort in custom order.

๐Ÿ“ Quick Quiz

1. Which header provides sort() and find()?

2. What does std::sort(v.begin(), v.end()) do by default?

3. binary_search requires the range to be: