range based for loop c++

A range-based for loop in C++ allows you to iterate over the elements of a container, such as an array or a vector, without explicitly specifying the loop counter or the bounds of the loop. The syntax of a range-based for loop is as follows:

for (auto element : container) {
    // code to be executed for each element

Here's a step-by-step explanation of how a range-based for loop works:

  1. The loop starts by declaring a variable element of type auto. The auto keyword allows the compiler to automatically deduce the type of element based on the type of the elements in the container.

  2. The range-based for loop then specifies the container over which the loop should iterate. This can be any container that provides an iterator, such as an array, a vector, a list, or even a user-defined container.

  3. For each iteration of the loop, the variable element is assigned the value of the current element in the container. The loop body is then executed using this value.

  4. After the loop body is executed for each element in the container, the loop terminates and program execution continues with the next statement after the loop.

It's important to note that the range-based for loop is designed for iterating over the elements of a container in a read-only manner. If you need to modify the elements of the container, you should use a regular for loop or a range-based for loop with a reference to the elements.

Here's an example to illustrate the usage of a range-based for loop:

#include <iostream>
#include <vector>

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

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

    return 0;


1 2 3 4 5

In this example, the range-based for loop iterates over each element in the numbers vector and prints it to the console. The loop automatically deduces the type of number as int based on the type of elements in the numbers vector.