Core Module
12 min forge
C++ STL Algorithms
Mastering built-in algorithms for sorting, searching, and manipulating containers.
C++ STL Algorithms
π What is it
The <algorithm> library provides functions for a variety of tasks (e.g., sorting, searching, transforming, and partitioning) on ranges of elements. It works elegantly with all STL containers.
β‘ When to use
Always! Never rewrite a sorting or searching algorithm from scratch unless specifically asked in an interview. STL algorithms are highly optimized.
π§ Time complexity
std::sort(): $O(N \log N)$std::binary_search(): $O(\log N)$ on sorted ranges.std::lower_bound()/std::upper_bound(): $O(\log N)$ on sorted ranges.
π» Code example
cpp Standard#include <algorithm> #include <vector> std::vector<int> v = {4, 2, 5, 1, 3}; std::sort(v.begin(), v.end()); // {1, 2, 3, 4, 5} auto it = std::lower_bound(v.begin(), v.end(), 3); // it points to 3
β Common mistakes
- Using binary search algorithms on unsorted ranges (leads to undefined behavior).
- Using
std::sortonstd::list(uselist::sort()instead because list iterators are not random access). - Forgetting that
lower_boundreturns an iterator, which needs to be dereferenced or checked againstend().