Iterators and Ranges

What is a Range in C++?

What is a range in C++ and how is it different from an iterator?

Abstract art representing computer programming

A range in C++ is a concept introduced in C++20, representing a sequence of elements with a beginning and an end, defined by begin() and end() methods. The main difference between iterators and ranges are:

  • Iterators: Provide a way to traverse through elements in a container. They act as pointers to elements.
  • Ranges: Encompass the entire sequence and provide the begin() and end() methods to obtain iterators.

Here's an example:

#include <vector>
#include <iostream>

int main() {
  std::vector<int> Vector{1, 2, 3};
  
  // Range-based for loop
  for (int x : Vector) { 
    std::cout << x << ", ";
  }
}
1, 2, 3,

In this example, Vector is a range, and the range-based for loop uses it to iterate over the elements.

This Question is from the Lesson:

Iterators and Ranges

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

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Iterators and Ranges

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

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved