C++ STL: Overview of <algorithm>

Michael Spagna
3 min readApr 18, 2021
C++ 20 | g++ 10.2.0 | Ubuntu 64-bit 20.04.2.0

Hi! This is going to be a series of posts exploring the C++ STL <algorithm> header. This is going to be a way to improve my understanding of the standard algorithms and give you, the reader, a simplified overview of each algorithm. I am not a professional writer and I will mostly be learning the algorithms along with you. I’ll definitely be making mistakes so if you notice any please reach out!

What is it?

The C++ Standard Library <algorithm> header is one of the most powerful headers in the entire STL. It contains 91 algorithms that can be divided into 11 categories (listed below).

When to use it?

Much like Spongebob’s opinion on striped sweaters the best time to use an STL algorithm is all the time. These algorithms can help make your code much shorter, cleaner, and have less bugs. If you are about to write a for loop pause and try to think if it can be replaced by an algorithm. If you’re about to implement your own algorithm like binary search or sort use the out of the box version from the STL. These algorithms have been implemented by people with way bigger brains than me. They have been tried and tested by developers all over the world. You can be confident they will function as promised.

How to use it?

#include <algorithm> //include the algorithm header in your project
#include <vector> //Algorithms work best with stl containers
#include <iostream>
#include <iterator>
int main()
{
std::vector<int> v1({8,6,9,13,1,2});
std::vector<int> v2({2,3,4,10,7,4});

std::sort(v1.begin(), v1.end()); //iterator based sort
std::ranges::sort(v2); //ranged based sort
//Print vector with std::copy and an ostream_iterator<int>
std::copy(v1.begin(), v1.end()
,std::ostream_iterator<int>(std::cout, " "));
std::cout << '\n'
//Print vector with std::ranges::for_each using a lambda
std::ranges::for_each(v2, [](int i)->void{std::cout << i<< ' ';});
}
Output:
1 2 6 8 9 13
2 3 4 4 7 10

--

--

Michael Spagna
0 Followers

Im just here to learn some things