cpp / expert
Snippet
Declarative Data Pipelines with Ranges and Views
C++20 Ranges allow for functional-style composition of algorithms using the pipe operator. Views are lazy, meaning the operations are only performed when the elements are actually accessed, which avoids temporary allocations and improves cache locality.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <ranges>#include <vector>#include <iostream>int main() {std::vector<int> nums = {1, 2, 3, 4, 5, 6};auto results = nums| std::views::filter([](int n) { return n % 2 == 0; })| std::views::transform([](int n) { return n * n; });for (int n : results) {std::cout << n << " "; // 4 16 36}}
Breakdown
1
| std::views::filter(...)
Creates a lazy view that only includes elements matching the predicate.
2
| std::views::transform(...)
Applies a transformation function to each element in the pipeline lazily.