More Everyday Problems
Learn and practice with algorithms to deal with everyday problems.
We'll cover the following...
Testing for certain conditions
There are three very handy algorithms called all_of()
, any_of()
, and none_of()
. They all take a range, a unary predicate (a function that takes one argument and returns true or false), and an optional projection function.
Let’s say we have a list of numbers and a small lambda that determines whether a number is negative or not:
const auto v = std::vector{3, 2, 2, 1, 0, 2, 1};const auto is_negative = [](int i) { return i < 0; };
We can check if none of the numbers are negative by using none_of()
:
const auto v = std::vector<int>{3, 2, 2, 3, 1, 2, 1};auto is_negative = [](int i) { return i < 0; };if (std::ranges::none_of(v, is_negative)) {std::cout << "Contains only whole numbers\n";}
Further, we can ask if all elements in the list are negative by using all_of()
:
const auto v = std::vector<int>{3, 2, 2, 1, 0, 2, 1};auto is_negative = [](int i) { return i < 0; };if (std::ranges::all_of(v, is_negative)) {std::cout << "Contains only negative numbers\n";}
Lastly, we can see whether the list contains at least one negative number using any_of()
:
const auto v = std::vector{3, 2, 2, 1, 0, 2, 1};auto at_least_negative = [](int i) { return i < 0; };if (std::ranges::any_of(v, at_least_negative)) {std::cout << "Contains at least one negative number\n";}
It’s easy to forget about these small, handy building blocks that reside in the standard library. But once we get into the habit of using them, we will never look back ...