Meeting std::algorithm in C++

Sohini Dhar
2 min readApr 4, 2021

--

I met “std::algorithm” when I was implementing an algorithm for my production code. I was new to C++ and would have always used the left-hand side approach as mentioned in the table. However, std::algorithm helped me to make my code shorter and solve a lot of complex problems easily.

What do you do if you want to add numbers in a vector, or find if a number exists in a container or not? Do you know that there exists an inbuilt function in C++ that can sort a container?

C++ has been very rich in its unique features and STL Algorithms are one of its unique gifts. I have been using quite a number of them in my work, however, a week back I got introduced to a hundred more in the talk by Jonathan Boccaro105 STL Algorithms in Less Than an hour”. Go watch it if you are interested. It shows how the C++ committee has thought about the problems we face in our daily lives and how we can solve them easily using simple algorithms. He presents a very beautiful map called “The World of C++ STL algorithms” where he groups each of them according to various families. The families range from the “Lands of Queries” to “Numerical Algorithms” to “Algorithms on Sets” and many more.

The grouping is done based on what type of operation you wish to do with a range of numbers. For example,

a. If you want to replace a number in a container with another number, you should use:

std::replace(vec.begin(), vec.end(), 42, 43) 
//This line will replace all the occurrences of 42 to 43.

b. If you want to check if all the numbers in a vector range are even not, you can use:

std::all_of(vec.begin(), vec.end(), [](int num) 
{
return num%2 == 0
})
// This line will return a Boolean value after checking if all the numbers in the container is even.

There is a lot more to learn and achieve if you have time to go through them all. But that will not be sufficient, use it in your production code and see the magic of algorithms. It will make your code smaller, prettier and fun to work with. In the same context, I will also recommend another talk by the founder of C++, Bjarne Stroustrup from the C++ Conference CPPCON 2014, “Make Simple Tasks Simple”. If you enjoy working with C++ you will enjoy these talks and STL Algorithms too.

Let me know what all methods from std::algorithm have you used. Don’t forget to like the article if you enjoyed reading it!

Happy C++ Coding!! Please follow, like, comment, share if you like this.

--

--

Sohini Dhar
Sohini Dhar

Written by Sohini Dhar

Programmer, Traveler, Adventurer!!!!

Responses (1)