Understanding Range Categories in C++

What are the different categories of ranges in C++?

Ranges in C++ are categorized based on the capabilities of their underlying iterators. There are many different categories of range, each with a different set of capabilities. The three most common types are:

  • Forward Range: Supports one-way traversal, such as std::forward_list.
  • Bidirectional Range: Supports two-way traversal, such as std::list.
  • Random-Access Range: Supports direct access to any element, such as std::vector.

Here's an example that checks the category of different ranges:

#include <vector>
#include <list>
#include <forward_list>
#include <ranges>
#include <iostream>

template <typename T>
void Log(T Range) {
  if constexpr (std::ranges::forward_range<T>) {
    std::cout << " - Forward Range\n";
  }
  if constexpr (std::ranges::bidirectional_range<T>) {
    std::cout << " - Bidirectional Range\n";
  }
  if constexpr (std::ranges::random_access_range<T>) {
    std::cout << " - Random Access Range\n";
  }
}

int main() {
  std::cout << "std::forward_list<int>:\n";
  Log(std::forward_list<int>{1, 2, 3});

  std::cout << "\nstd::list<int>:\n";
  Log(std::list<int>{1, 2, 3});

  std::cout << "\nstd::vector<int>:\n";
  Log(std::vector<int>{1, 2, 3});
}
std::forward_list<int>:
 - Forward Range

std::list<int>:
 - Forward Range
 - Bidirectional Range

std::vector<int>:
 - Forward Range
 - Bidirectional Range
 - Random Access Range

Iterators and Ranges

This lesson offers an in-depth look at iterators and ranges, emphasizing their roles in container traversal

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

How to Use Iterators in C++
How do I use iterators with different containers in C++?
What is a Range in C++?
What is a range in C++ and how is it different from an iterator?
Using Range-Based For Loops in C++
How do I use range-based for loops in C++?
Passing by Reference in Range-Based For Loops
Why should I pass by reference in range-based for loops in C++?
Using Concepts in C++
How do I use concepts in C++ to check if a type is a range?
Ask Your Own Question
Get an immediate answer to your specific question.