C++ ranged for loop


The ranged for loop (introduced in C++11) simplifies iteration over elements in containers like arrays, vectors, and other collections. Instead of manually managing an index or iterator, the ranged for loop allows you to directly access each element in the container.

The basic syntax of the ranged for loop in C++ is:

for (declaration : container) {
    // Code to process each element
}

Where:

  • declaration: A reference (or copy) of the current element in the container.
  • container: The collection you are iterating over (such as an array, vector, or list).

This loop type provides a cleaner, more readable, and less error-prone way of iterating through elements compared to traditional for loops.


Syntax of the Ranged For Loop

for (auto& element : container) {
    // Use element here
}
  • auto& element: auto automatically deduces the type of the element. Using & ensures that you are modifying the elements by reference, preventing unnecessary copies.
  • container: This can be any iterable container, such as an array, vector, or list.

If you do not need to modify the elements and only need to read them, you can omit the & to iterate over a copy of each element.

for (auto element : container) {
    // Read element (copy) but don't modify
}

Example 1: Ranged For Loop with an Array

In this example, we will use a ranged for loop to iterate over the elements of a C++ array.

#include <iostream>

int main() {
    int arr[] = {10, 20, 30, 40, 50};

    // Iterate using ranged for loop
    for (auto element : arr) {
        std::cout << element << " ";
    }

    return 0;
}

Output:

10 20 30 40 50

Explanation:

  • The loop automatically iterates through each element in the array arr.
  • auto deduces the type of element as int because the array holds integers.
  • Each element is printed in the loop body.

Example 2: Ranged For Loop with a Vector

Vectors are one of the most commonly used containers in C++. This example demonstrates using a ranged for loop with a vector.

#include <iostream>
#include <vector>

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

    // Iterate using ranged for loop
    for (auto element : vec) {
        std::cout << element << " ";
    }

    return 0;
}

Output:

1 2 3 4 5

Explanation:

  • We use a ranged for loop to iterate over the vector vec and print its elements.
  • Since auto deduces the type as int, it works seamlessly for the vector of integers.

Example 3: Ranged For Loop with a Reference

When iterating over large containers, using references (with auto&) avoids copying elements and can improve performance. Here's an example of modifying the elements of a vector:

#include <iostream>
#include <vector>

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

    // Modify elements using ranged for loop and reference
    for (auto& element : vec) {
        element *= 2;  // Double each element
    }

    // Print the modified elements
    for (auto element : vec) {
        std::cout << element << " ";
    }

    return 0;
}

Output:

2 4 6 8 10

Explanation:

  • The ranged for loop iterates over each element of the vector vec by reference (auto&).
  • Each element is modified by multiplying it by 2.
  • The modified vector is printed, showing the doubled values.

Example 4: Ranged For Loop with a Constant Reference

If you want to avoid modifying the elements of a container and just read them, it's a good practice to use a constant reference to prevent accidental modification.

#include <iostream>
#include <vector>

int main() {
    std::vector<int> vec = {10, 20, 30, 40, 50};

    // Use constant reference to avoid modification
    for (const auto& element : vec) {
        std::cout << element << " ";
    }

    return 0;
}

Output:

10 20 30 40 50

Explanation:

  • The const auto& ensures that we only have a read-only reference to each element in the vector. This prevents modification and is more efficient for large data types (like complex objects).

Example 5: Ranged For Loop with String

The ranged for loop also works with C++ strings, allowing you to iterate over individual characters.

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, World!";

    // Iterate over characters of a string
    for (auto ch : str) {
        std::cout << ch << " ";
    }

    return 0;
}

Output:

H e l l o ,   W o r l d !

Explanation:

  • The loop iterates over each character in the string str.
  • auto deduces the type of ch as char, allowing us to print each character individually.