Last year, I wrote a blog post about new C++23 range adaptors for joining and zipping. The C++23 standard includes a longer lists of range adapters (you can find a list here). Among them, there are several adaptors used for creating views consisting of chunks or “windows” of the elements of a given range. In…
Tag: ranges
Express one of multiple options in a nice way
We often find ourselves writing if statements where a variable is compared with several values either to check if it matches one of them or that it doesn’t match any. Here is an example:
int option = ...; // at lease a value is matched if (option == 12 || option == 23 || option == 42) { std::cout << "it's a good option\n"; } // no value is matched if (option != 12 && option != 23 && option != 42) { std::cout << "it's a bad option\n"; }
This example has three comparison values for each case, but it could be 5, or 10, or any number. If it’s too many then perhaps a different approach should be taken. However, the question is, how do we express this in a simpler way in C++, rather than a long if condition?
A custom C++20 range view
Some time ago, I wrote a short post about the C++20 ranges library with examples of how it can simplify our code. Let me take a brief example. Give a sequence of numbers, print the last two even numbers, but in reverse order.
C++ code samples before and after Ranges
The Ranges library proposal has been accepted for C++20 at the San Diego meeting of the standard committee in November last year. The library provides components for handling ranges of values aimed at simplifying our code. Unfortunately, the Ranges library is not very well documented, which makes it harder to grasp for those that want to learn it. This post is intended as an introduction based on examples of code written with and without Ranges.