Solving Everyday Problems
Learn some useful algorithms to deal with different programming scenarios efficiently.
We'll cover the following...
We will list some common scenarios and useful algorithms to give you a taste of the algorithms available in the standard library. There are many algorithms in the library, but we will only present a few of them in this lesson.
Iterating over a sequence
It’s useful to have a short helper function that can print the elements of a sequence. The following generic function works with any container that holds elements that can be printed to an output stream using operator<<()
:
void print(auto&& r) {std::ranges::for_each(r, [](auto&& i) { std::cout << i << ' '; });}
The print()
function is using for_each()
, which is an algorithm imported from the <algorithm>
header. for_each()
calls the function that we provide once for each element in the range. The return value of the function we provide is ignored and has no effect on the sequence we pass to for_each()
. We can use for_each()
for side effects such as printing to stdout
(which we do in this example).
A similar, very general algorithm is transform()
. It also calls a function for each element in a sequence, but instead of ignoring the return value, it stores the return value of the function in an output sequence, like this:
auto in = std::vector{1, 2, 3, 4};auto out = std::vector<int>(in.size());auto lambda = [](auto&& i) { return i * i; };std::ranges::transform(in, out.begin(), lambda);print(out);// Prints: "1 4 9 16"
This code snippet also demonstrates how we can use our print()
function defined earlier. The transform()
algorithm will call our lambda once for each element in the input range. To specify where the output will be ...