C++20 Range in 30 sec

Mana Tako
2 min readJul 8, 2023

The C++20 standard brought an array of useful features into the hands of developers, one of which is the Ranges library. This library introduces “lazy evaluation”, a technique that offers a new level of efficiency.

Today, to demonstrate the transformative power of this feature with a simple yet revealing example. I’ve created a 30-second video tutorial, which you can find embedded below, to guide you through this comparison of the traditional approach to the C++20 Ranges approach.

The traditional approach demonstrating here involves creating a new vector to store the squares of even numbers from an existing vector. This old method works fine but requires a significant amount of memory and two full iterations over the vector, which can be costly in terms of CPU time.

Now, let’s explore the smarter approach using C++20 Ranges:

Here, the filtering and transformation operations are not performed until we actually iterate through the result. This lazy evaluation reduces memory usage and CPU time. The code is simpler, cleaner, and definitely smarter.

Conclusion: C++20 Ranges represents a leap forward in programming efficiency. It doesn’t just make our code more readable; it also makes it more efficient by optimizing resource usage. If you haven’t yet, it’s time to embrace C++20 and the power of lazy evaluation.

Remember, it’s not always about writing code that works. It’s about writing code that works well.

--

--

Mana Tako

Welcome! As a dev with 10+ Nordic exp, I bring unique insights on diversity, well-being, and innovation. Join me to explore software dev, AI, and more!