0
0
CppConceptBeginner · 3 min read

What is Ranges in C++: Explanation and Examples

In C++, ranges are a modern way to work with sequences of elements using a set of components that simplify iteration and transformation. They provide a clean, readable, and composable approach to process collections without explicit loops.
⚙️

How It Works

Ranges in C++ let you think about collections like arrays or lists as whole objects you can manipulate easily. Instead of writing loops to go through each item, you use range-based views and actions that describe what you want to do, like filtering or transforming.

Think of ranges like a conveyor belt in a factory. Instead of picking up each item yourself, you set up machines (called views) that automatically pick, change, or sort items as they move along. This makes your code cleaner and easier to understand.

Ranges are built on top of iterators but hide the complexity, so you focus on what you want to do with the data, not how to move through it step-by-step.

💻

Example

This example shows how to use ranges to filter and transform a list of numbers, printing only the even numbers doubled.

cpp
#include <iostream>
#include <vector>
#include <ranges>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5, 6};

    // Create a range that filters even numbers and doubles them
    auto even_doubled = numbers | std::ranges::views::filter([](int n) { return n % 2 == 0; })
                                 | std::ranges::views::transform([](int n) { return n * 2; });

    for (int n : even_doubled) {
        std::cout << n << ' ';
    }
    std::cout << '\n';
    return 0;
}
Output
4 8 12
🎯

When to Use

Use ranges when you want to write clear and concise code to process collections without manual loops. They are great for filtering, transforming, and combining data in a readable way.

For example, if you have a list of user data and want to find all users above a certain age and then extract their names, ranges let you do this in a simple chain of operations.

Ranges improve code maintainability and reduce errors by avoiding explicit iterator management.

Key Points

  • Ranges provide a modern, composable way to work with sequences in C++.
  • They use views to create lazy, efficient transformations without copying data.
  • Ranges simplify code by hiding iterator details and loops.
  • Introduced in C++20, they require a compatible compiler.

Key Takeaways

Ranges let you process collections with simple, readable code instead of manual loops.
They use views to filter and transform data lazily and efficiently.
Ranges improve code clarity and reduce errors by hiding iterator details.
They are part of C++20 and later standards, so use a modern compiler.
Use ranges for tasks like filtering, mapping, and combining sequences cleanly.