🔗beginner
Ranges Basics
Introduction to the ranges library and range-based algorithms
Example Code
cpp
#include <ranges>#include <vector>#include <iostream>#include <algorithm>int main() { std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // Traditional algorithm std::vector<int> result1; std::copy_if(numbers.begin(), numbers.end(), std::back_inserter(result1), [](int n) { return n % 2 == 0; }); // Range-based algorithm - cleaner syntax auto result2 = numbers | std::views::filter([](int n) { return n % 2 == 0; }); std::cout << "Even numbers: "; for (int n : result2) { std::cout << n << " "; } std::cout << std::endl; // Output: 2 4 6 8 10 return 0;}Explanation
Ranges provide a more composable and readable way to work with sequences. The pipe operator (|) allows chaining operations, and views are lazy - they don't create intermediate containers.
Key Points
- 1Ranges work directly on containers
- 2Pipe operator (|) chains operations
- 3Views are lazy - computed on demand
- 4No intermediate containers needed