Home Item 26 - Range-based for Loop Enhancements(English)
Post
Cancel

Item 26 - Range-based for Loop Enhancements(English)

Range-based for Loop Enhancements

Let’s talk about a relatively small enhancement. C++20 supports initialization statements and initializers in the range-based for loop.

Let’s look directly at the code!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <vector>

int main() {
    // Using range-based for loop with an initialization statement
    for (std::vector<int> vec = {1, 2, 3, 4, 5}; int n : vec) {
        std::cout << n << " ";
    }
    std::cout << std::endl;

    // Using range-based for loop with variable initialization
    int totalSum = 0;
    for (int sum = 0; int i : {1, 2, 3, 4, 5}) {
        sum += i;
        totalSum += sum;
        std::cout << "Current sum: " << sum << ", Total sum: " << totalSum << std::endl;
    }

    return 0;
}

Explanation: Vector Initialization:

n for (std::vector vec = {1, 2, 3, 4, 5}; int n : vec), vec is initialized in the loop header and then used in the loop body. int n : vec is used to iterate over each element in the vector vec. The output result is: 1 2 3 4 5.

Variable Initialization:

In for (int sum = 0; int i : {1, 2, 3, 4, 5}), sum is initialized in the loop header.

int i : {1, 2, 3, 4, 5} is used to iterate over each element in the initializer list {1, 2, 3, 4, 5}.

In the loop body, the value of sum is updated in each iteration, and the total sum totalSum is also updated in each iteration.

Execution Result

Desktop View

Benefits

This enhancement allows the range-based for loop to not only conveniently iterate over collections but also perform initialization operations in the loop header, making the code more concise and readable.

☝ツ☝

This post is licensed under CC BY 4.0 by the author.

👈 ツ 👍