← Back to C++ Course | Chapter 13: STL Containers & Algorithms | Lesson 6 of 15

C++ STL Algorithms

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

cpp
#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;
}

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

cpp
#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;
}

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

cpp
#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;
}

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

cpp
#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;
}

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

cpp
#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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.