C++ STL Algorithms
In this page:
Sorting with std::sort
std::sort rearranges the elements of a container into ascending order by default, using an efficient introsort implementation under the hood, and accepts an optional custom comparison function when you need a different ordering.
Example: Sorting with std::sort
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> nums = {5, 2, 8, 1};
std::sort(nums.begin(), nums.end());
for (int n : nums) std::cout << n << " ";
std::cout << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Finding with std::find
std::find searches a range for the first element equal to a given value and returns an iterator pointing to it — or an iterator equal to the range's end if no match exists, which you check for before dereferencing the result.
Example: Finding with std::find
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> nums = {1, 2, 3, 4};
auto it = std::find(nums.begin(), nums.end(), 3);
std::cout << (it != nums.end()) << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Counting with std::count
std::count tells you exactly how many times a specific value appears within a range, while its companion count_if lets you count elements that satisfy a custom predicate instead of matching an exact value.
Example: Counting with std::count
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> nums = {1, 2, 2, 3, 2};
std::cout << std::count(nums.begin(), nums.end(), 2) << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Modifying Vectors
Modifying algorithms like std::reverse and std::replace let you transform a container's contents in place — reversing element order, or swapping every occurrence of one value for another — without writing a manual loop yourself.
Example: Modifying Vectors
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> nums = {1, 2, 3};
std::reverse(nums.begin(), nums.end());
for (int n : nums) std::cout << n << " ";
std::cout << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Min and Max Functions
The standard library also provides simple std::min and std::max functions for comparing individual values, alongside std::min_element and std::max_element for finding the smallest or largest element across an entire range.
Example: Min and Max Functions
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> nums = {5, 2, 8, 1};
auto maxIt = std::max_element(nums.begin(), nums.end());
std::cout << *maxIt << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first: