Iterators and Ranges

Using Range-Based For Loops in C++

How do I use range-based for loops in C++?

Abstract art representing computer programming

Range-based for loops provide a simpler syntax for iterating over elements in a range. Using a range-based for loop involves two steps:

  1. Declare the Loop: Use the for keyword followed by the element type, a reference if needed, and the range.
  2. Access Elements: Inside the loop, you can access each element directly.

Here's an example:

#include <vector>
#include <iostream>

int main() {
  std::vector<int> Vector{1, 2, 3};

  for (const int& x : Vector) { // Using const reference
    std::cout << x << ", ";
  }
}
1, 2, 3,

Using a reference (const int& x) avoids copying elements, which is beneficial for large or complex types.

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