Search⌘ K
AI Features

More Everyday Problems

Explore how to apply common C++ standard library algorithms to solve everyday programming problems efficiently. Learn to test conditions with all_of, any_of, none_of, count elements using both count and equal_range, and simplify code with min, max, clamp, and minmax functions. This lesson helps you write clearer and faster code by leveraging built-in algorithms, improving your productivity and understanding of standard utilities.

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:

C++
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():

C++
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():

C++
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():

C++
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 ...