c++c++20range-based-loop

What does the auto "t{1U}" do in the following range-based for loop from std::make_heap example?


I was browsing the standard algorithm library and came across an example which used a range based for loop in a way that I had not seen before: https://en.cppreference.com/w/cpp/algorithm/is_heap

In the example given, they use a range based for loop to iterate over the vector of integers:

for (auto t{1U}; auto i : v)
    std::cout << i << (std::has_single_bit(++t) ? " | " : " ");

I am familiar with the most commonly used range-based for loop. E.g.

for (const auto& elem : vector)
{
    // do something with elem
}

However, I was confused to see auto t{1U}, I had never seen that before and was wondering what the did?

It looks like it might be a temporary range expression: https://en.cppreference.com/w/cpp/language/range-for But I am still confused about what t actually is and also why it's needed here?


Solution

  • If you look at the range-based reference you yourself link to, you will see that the syntax contains a clause called init-statement (optional).

    auto t{1U}; is that optional init-statement.

    It's simply a way to define one or more variables inside the scope of the loop.

    So

    for (auto t{1U}; auto i : v)
        std::cout << i << (std::has_single_bit(++t) ? " | " : " ");
    

    is basically equivalent to

    {
        auto t{1U};  // The same as unsigned t = 1;
    
        for (auto i : v)
            std::cout << i << (std::has_single_bit(++t) ? " | " : " ");
    }
    

    It might be worth noting that the if statement have had such a init-statement since the C++17 standard.