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.
#include <algorithm>
#include <vector>
std::vector<int> v = {3, 1, 2};
std::sort(v.begin(), v.end());
for (int x : v) std::cout << x;123sort() rearranges the vector into ascending order in-place.
std::vector<int> v = {1,2,3};
auto it = std::find(v.begin(), v.end(), 2);
std::cout << (it != v.end());1find() 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.
