英文:
What does the auto "t{1U}" do in the following range-based for loop from std::make_heap example?
问题
我正在浏览标准算法库,并发现一个示例中使用了一种我以前没有见过的范围基础循环的方式:https://en.cppreference.com/w/cpp/algorithm/is_heap
在给定的示例中,他们使用范围基础循环来遍历整数向量:
for (auto t{1U}; auto i : v)
std::cout << i << (std::has_single_bit(++t) ? " | " : " ");
我熟悉最常用的范围基础循环,例如:
for (const auto& elem : vector)
{
// 对 elem 做一些操作
}
然而,我对auto t{1U}
感到困惑,以前从未见过这样的写法,想知道它的作用是什么?
看起来它可能是一个临时的范围表达式:
https://en.cppreference.com/w/cpp/language/range-for
但我仍然不清楚t
实际上是什么,以及为什么在这里需要它?
英文:
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?
答案1
得分: 6
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 has had such a init-statement since the C++17 standard.
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论