C++ STL Algorithm Library
Last Updated :
21 Aug, 2025
Algorithms are ready-made functions that help you perform common operations like searching, sorting, counting, and comparing on containers (like arrays, vectors, sets, etc.).
These algorithms are defined in the <algorithm> and <numeric> header files.
Type of Algorithms
We can divide the algorithms into following parts:
- Searching Algorithms
- Sorting and Rearranging Algorithms
- Manipulation Algorithms
- Counting and Comparing Algorithms
1. Searching Algorithms
These are used to find elements in a container.
Function | Description | Example |
---|
find() | Finds the first occurrence of a value | find(v.begin(),v.end(),10); |
---|
find_if() | Finds the first element matching a condition | find_if(v.begin(),v.end(),[](int x){ return x>5;}); |
---|
binary_search | Checks if a value exists in sorted data | binary_search(v.begin(),v.end(),7); |
---|
Note: binary_search() only works on sorted containers.
2. Sorting and Rearranging Algorithms
These change the order or position of elements.
Function | Description | Example |
---|
sort() | Sorts elements in ascending order | sort(v.begin(), v.end()); |
---|
reverse() | Reverses the order of elements | reverse(v.begin(), v.end()); |
---|
rotate() | Rotates elements around a position | rotate(v.begin(), v.begin()+2,v.end()); |
---|
Note: We can use custom comparators with sort() for descending or custom order.
3.Manipulation Algorithms
These change or update values in the container.
Function | Description | Example |
---|
fill() | Fills range with a value | fill(v.begin(), v.end(),0); |
---|
replace() | Replaces all matching elements | replace(v.begin(), v.end(),3,9); |
---|
copy() | Copies one container to another | copy(v.begin(), v.end(),out.begin()); |
---|
remove() | Removes value (logically) | remove(v.begin(), v.end(), 5); |
---|
Note: remove() doesn't actually shrink the container -- use erase() with it.
4. Counting & Comparing Algorithms
These check or count elements based on conditions.
Function | Description | Example |
---|
count() | Counts how many times a value appears. | count(v.begin(), v.end(), 5); |
---|
count_if() | Counts based on a condition | count_if(v.begin(), v.end(), [] (int x){ return x>5;}); |
---|
min()/ max() | Finds min or max of two values | min(3, 7); or max(10, 6); |
---|
min_element() | Finds smallest in a range | min_element(v.begin(), v.end()); |
---|
equal() | Checks if two ranges are same | equal(a.begin(), a.end(), b.begin()); |
---|
Explore
Introduction to C++
Basics
Core Concepts
C++ OOP
Standard Template Library(STL)
Practice C++
Top C++ DSA Related Problems