range-based


Concept: range-based for loops

The range-based for loop, introduced in C++11, is a simplified way to iterate over elements in a collection (such as arrays, vectors, or any other container that supports iteration). It provides a more concise and readable alternative to traditional for loops, especially when working with containers from the Standard Template Library (STL).

Basic Syntax

The syntax for a range-based for loop is:

for (declaration : expression) {
    // loop body
}

Example1: Iterating Over a Vector

Here's a simple example of using a range-based for loop to iterate over the elements of a std::vector:

#include <iostream>
#include <vector>

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

    // Range-based for loop to iterate over the vector
    for (int n : numbers) {
        std::cout << n << " ";
    }
    std::cout << std::endl;

    return 0;
}

Expected Output

1 2 3 4 5

Explanation

Example 2: Working with Const Containers

When iterating over containers that should not be modified, you can use const references:

#include <iostream>
#include <vector>

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

    // Range-based for loop with a const reference
    for (const int& n : numbers) {
        std::cout << n << " ";
    }
    std::cout << std::endl;

    return 0;
}

Expected Output

Expected Output

1 2 3 4 5

Explanation

Example3: Range-Based For Loops with Arrays

Range-based for loops also work with arrays, both static and dynamic:

#include <iostream>

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

    // Range-based for loop to iterate over an array
    for (int n : arr) {
        std::cout << n << " ";
    }
    std::cout << std::endl;

    return 0;
}

Expected Output

10 20 30 40 50

Explanation

Example 4: auto Keyword in Range-Based For Loops

You can simplify the loop even further using the auto keyword, allowing the compiler to deduce the type:

#include <iostream>
#include <vector>

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

    // Range-based for loop using auto
    for (auto& n : numbers) {
        n += 5;
    }

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

    return 0;
}

Expected Output

6 7 8 9 10

Explanation

Range-Based For Loop with Custom Containers

Conclusion

Range-based for loops simplify the iteration over containers and arrays in C++, making the code more concise and easier to read. They are versatile and can be combined with references, the const keyword, and the auto keyword to create flexible and efficient loops that avoid common pitfalls associated with traditional loop constructs. This feature is especially useful in modern C++ programming, where readability and safety are key concerns.

Previous Page | Course Schedule | Course Content