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::sort on std::list (use list::sort() instead because list iterators are not random access).
  • Forgetting that lower_bound returns an iterator, which needs to be dereferenced or checked against end().