🔗intermediate
Composing Views
Chain multiple views to create complex data transformations
Example Code
cpp
#include <ranges>#include <vector>#include <iostream>#include <string>int main() { std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // Compose multiple views: filter -> transform -> take auto pipeline = numbers | std::views::filter([](int n) { return n % 2 == 0; }) // Keep even | std::views::transform([](int n) { return n * n; }) // Square them | std::views::take(3); // First 3 std::cout << "Result: "; for (int n : pipeline) { std::cout << n << " "; // Output: 4 16 36 } std::cout << std::endl; // String processing example std::string text = " Hello, World! "; auto words = text | std::views::split(' ') | std::views::filter([](auto word) { return !std::ranges::empty(word); }); return 0;}Explanation
Views can be composed into pipelines where each view transforms the data. The entire pipeline is lazy - elements are processed one at a time as they're consumed, making it memory-efficient.
Key Points
- 1filter - keep elements matching predicate
- 2transform - apply function to each element
- 3take/drop - limit or skip elements
- 4Pipelines are evaluated lazily