As I listened to quite a few talks about the importance of using C++ STL algorithms, I realized I needed to practice using them myself. This repository will provide simple examples for each algorithm. The target audience is C++ beginners, in hopes to show them the simplicity and power of these algorithms. Use this not as a replacement, but as another source of examples that can be quickly read and understood.
Given a std::vector v
of integers:
// Determines whether 'v' contains 4. bool contains_four = false; for (int i = 0; i < v.size(); ++i) { if (i == 4) { contains_four = true; break; } }
This could be improved upon by using a range-based loop:
// Determines whether 'v' contains 4. bool contains_four = false; for (const int i : v) { if (i == 4) { contains_four = true; break; } }
Even better though, is using std::any_of
:
// Determines whether 'v' contains 4. const bool equals_four = std::any_of(v.cbegin(), v.cend(), [](int i)->bool{ return i == 4; });
Here, we've taken a raw for loop
and replaced it with an STL algorithm that, in one line, tells us more clearly what is occurring. This improves readability, minimizes number of lines of code, and provides (likely) the best algorithm for what you're trying to do.
With the release of C++20, this will simplify even further using ranges:
const bool equals_four = std::ranges::any_of(v, [](int i)->bool{ return i == 4; });