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?