C++11 range based loop: How does it really work

前端 未结 3 1779
梦毁少年i
梦毁少年i 2020-12-03 22:02

I know how this loop works, and how I can use it in practical problems. But I want to know what is happening under the hood. I thought that this loop was similar to a regula

3条回答
  •  时光说笑
    2020-12-03 22:30

    The range-based for-loop is indeed somewhat different than the classical for-loop in this regard. The declaration you provide (const int x) is declared for every iteration separately, in contrast to classical for-loops.

    To be more precise:

    for (const int x : vec) {
        cout << x << endl;
    }
    

    is just a shorthand for (and simply replaced with) the following "classical iterator loop":

    for (auto it = vec.begin(), e = vec.end(); it != e; ++it) { 
        const int x = *it; 
        cout << x << endl; 
    }
    

    (except that it and e are not available in the body; also vec is actually "saved" in a separate variable; but let's not focus on unimportant details here; the exact definition of range-based for loop can be looked up here)

    Note that const int x is declared and initialized to *it inside the loop body! So it is initialized in every iteration, rather than changed.

提交回复
热议问题