简体   繁体   中英

range based for loop vs regular iterator for loop

Consider the following code example :

#include<iostream>
#include<vector>
#include<typeinfo>

int main(){
    std::vector<int> v = {1 ,2,4};
    for(auto &i:v)  std::cout<<typeid(i).name();
    for(auto k = v.begin(); k!=v.end();++k) std::cout<<typeid(k).name();
    return 0;
}

The first loop represents range based for-loops , and second one are regular for loops with iterators. I have used regular ones a lot , and from my experience , auto k is of type of iterator , while range based loops had type of auto i as int. Output of above program is:

i & N9__gnu_cxx17__normal_iteratorIPiSt6vectorIiSaIiEEEE

Is this normal behavior for range based for loops over collections like vectors ( somewhere mentioned) ? Because someone (like me) would assume range based for loops are just shorthand for regular for loops.

The answer is what Magnus already stated: Yes, it is a normal behavior . Range loops are for cases when we are interested in examining every item in a collection (unless we break out sooner) and aren't interested in doing anything with the container itself. Like it was already stated, range loops are optimized that way , eg it indeed computes the finishing condition only once. In my opinion, this is a very nice and welcome addition to the variety of loop options in c++, since we do often face this very exact situation: we get a container and are interested in simply going through them one by one in either const or non-const fashion.

range based for loop will give container element.

exa:

vectorv{5,7,10};

for(auto i:v)

cout<<i ; //5,7,10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM