Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

c++ - What is "for (x : y)"?

So i was looking around on the interwebs about threads and i came to a blog/tutorial thing about threads but what confused me was this line that he used

for (auto& thread : threads)  

not really sure what that does
Here is a link to the blog i'm talking about LINK
Thanks to whoever answers this question for me
PS can you also give me a reference so i can read up on what that does and other related things I seem to be blind when searching for one

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

C++11 introduced a new iteration statement, the so-called range-based for loop. It differs from the ordinary for loop in that it only gives you access to the members of a range, without requiring you to name the range itself explicitly and without using proxy iterator objects. Specifically, you are not supposed to mutate the range during the iteration, so this new loop documents the intent to "look at each range element" and not do anything complicated with the range itself.

The syntax is this: for (decl x : r) { /* body */ }, where decl stands for some declaration and r is an arbitrary expression. This is functionally mostly equivalent to the following traditional loop:

{
    auto && __r = r;

    using std::begin;
    using std::end;

    for (auto __it = begin(__r), __e = end(__r); __it != __e; ++__it)
    {
        decl x = *it;
        /* body */
    }
}

As a special case, arrays and braced lists are also supported natively.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...