Range-Based For

suggest change

A range-based for loop iterates over a range without an explicit numeric index or iterator. The std::vector below uses class template argument deduction, which is C++17:

#include <iostream>
#include <vector>

int main() {
    std::vector values{0.4F, 12.5F, 16.234F};

    for (float value : values) {
        std::cout << value << ' ';
    }
    std::cout << '\n';
}

This will iterate over every element in values, with value getting the value of the current element. The following statement:

for (for-range-declaration : for-range-initializer ) statement

is equivalent to:

{
    auto&& __range = for-range-initializer;
    auto __begin = begin-expr, __end = end-expr;
    for (; __begin != __end; ++__begin) {
        for-range-declaration = *__begin;
        statement
    }
}

Since C++17, the begin and end expressions may have different types:

{
    auto&& __range = for-range-initializer;
    auto __begin = begin-expr;
    auto __end = end-expr; // end is allowed to be a different type than begin in C++17
    for (; __begin != __end; ++__begin) {
        for-range-declaration = *__begin;
        statement
    }
}

This permits sentinel-based ranges whose end marker has a different type from its iterator.

In this case, our loop is equivalent to:

{
    auto&& __range = values;
    auto __begin = values.begin(), __end = values.end();
    for (; __begin != __end; ++__begin) {
        float value = *__begin;
        std::cout << value << ' ';
    }
}

value is a copy of the current element. If elements are expensive to copy and the loop does not modify them, prefer const auto&. You do not have to use auto; an explicitly written type is also valid when the element can initialize it.

If you need access to the iterator, range-based for cannot help you (not without some effort, at least).

If you wish to reference it, you may do so:

std::vector<float> v{0.4F, 12.5F, 16.234F};

for (float& val : v)
{
    std::cout << val << " ";
}

You could iterate on const reference if you have const container:

const std::vector<float> v{0.4F, 12.5F, 16.234F};

for (const float& val : v)
{
    std::cout << val << " ";
}

One would use forwarding references when the sequence iterator returns a proxy object and you need to operate on that object in a non-const way. Note: it will most likely confuse readers of your code.

std::vector<bool> v(10);

for (auto&& val : v)
{
    val = true;
}

The “range” type provided to range-based for can be one of the following:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents