Site icon ucdev

Range-Based For Loop in C++: Syntax and Examples

close up of computer keyboard

Photo by Pixabay on Pexels.com

Reading Time: 3 minutes

In C++, the traditional for loop, well known from the C programming language, is still fully supported and widely used. It provides precise control over iteration, including the starting index, termination condition, and increment.

For example, we can iterate over a vector using a traditional for loop:

std::vector<int> numbers {10, 20, 30, 40, 50};

for (size_t i = 0; i < numbers.size(); i++) {
    std::cout << numbers[i] << " ";
}

However, when we simply want to iterate over every element of a container, such as a std::vector or std::string, manually managing an index is often unnecessary. To simplify this common operation, C++11 introduced the range-based for loop, which provides a cleaner and more readable way to iterate over arrays and containers.

The previous example can be rewritten as:

for (int num : numbers) {
    std::cout << num << " ";
}

Boot loops will produce the same output. The range-based approach eliminates the need to declare an index, check the container’s size, or manually increment a counter.

Range-Based For Loop Syntax

The general syntax is:

for (declaration : range) {
    // Process each element
}

The loop automatically visits each element of the specified range. For example:

std::vector<int> numbers {10, 20, 30};

for (int num : numbers) {
    std::cout << num << " ";
}

Using auto and References in Range-Based For Loops

Instead of explicitly specifying the element type, C++ allows us to use auto:

for (auto num : numbers) {
    std::cout << num << " ";
}

However, there is an important difference between iterating by value and by reference.

Let’s look at the example below. In both cases we modify the num variable, but in first loop, this is a copy, so origin data will not be modified. Only the second loop modifies the origin data.

// Iterating by value
for (auto num : numbers) {
    num += 5;  // Original vector is unchanged
}

// Iterating by reference
for (auto& num : numbers) {
    num += 5;  // Original vector is modified
}

If we want to iterate by reference, but want to prevent modification of the iterated object, we can use const reference. Iterating by const reference avoids unnecessary copies while preventing modification. Using const auto& is particularly useful when working with larger objects, such as std::string or custom classes.

for (const auto& num : numbers) {
    std::cout << num << " ";
}

Range-Based For Loops with Strings

A range-based loop can also iterate over individual characters in a string:

std::string text {"Hello"};

for (char c : text) {
    std::cout << c << " ";
}

Can You Iterate Over Two Strings Simultaneously?

A standard range-based for loop cannot directly iterate over two containers simultaneously. The simplest solution is a traditional-indexed loop:

#include <algorithm>
#include <string>

std::string s1 {"Hello"};
std::string s2 {"World"};

for (size_t i = 0; i < std::min(s1.size(), s2.size()); ++i) {
    std::cout << s1[i] << " vs " << s2[i] << '\n';
}

However, C++23 introduced std::views::zip, which makes this possible using a range-based loop:

#include <ranges>

for (auto [c1, c2] : std::views::zip(s1, s2)) {
    std::cout << c1 << " vs " << c2 << '\n';
}

The loop automatically stops when the shorter string ends, but remember, this feature requires a C++23-compatible standard library implementation.

Range-Based For Loop vs Traditional For Loop

Range-Based For LoopTraditional For Loop
Introduced in C++11Available since early C++
No manual index requiredIndex can be controlled
Ideal for processing all elementsIdeal when an index is needed
Cleaner and shorter syntaxMore flexible iteration control

Summary

The range-based for loop in C++ is a convenient alternative to traditional loops when processing arrays and containers. Remember these three common forms:

For most read-only operations on larger objects, const auto& is a good default choice. The traditional for loop remains an important part of C++ and is often preferable when you need an index or more precise control over iteration.

Exit mobile version