How do I use ranges::views::filter and transform in C++?

The `ranges::views::filter` and `ranges::views::transform` are part of the C++20 Ranges library, enabling a more expressive way to work with sequences of data. These views allow for lazy evaluation, meaning that data is processed only when needed.

The `filter` view is used to select elements from a range that satisfy a specific predicate, while the `transform` view applies a transformation to each element of the range.

Here’s an example demonstrating the use of both `ranges::views::filter` and `ranges::views::transform`:

#include <iostream> #include <ranges> #include <vector> int main() { std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; auto filtered_transformed = numbers | std::views::filter([](int n) { return n % 2 == 0; }) | std::views::transform([](int n) { return n * n; }); for (int n : filtered_transformed) { std::cout << n << " "; } return 0; }

In this example, we filter the numbers to keep only the even ones and then transform each of those numbers to its square. The resulting output will be the squares of even numbers from the original list.


C++ ranges views filter transform C++20 programming code examples Ranges library.