Abhinav Gauniyal
Abhinav Gauniyal

Reputation: 7574

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.

Upvotes: 7

Views: 10974

Answers (2)

Ramanand Yadav
Ramanand Yadav

Reputation: 329

range based for loop will give container element.

exa:

vectorv{5,7,10};

for(auto i:v)

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

Upvotes: -2

Arnošt L&#246;bel
Arnošt L&#246;bel

Reputation: 146

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, e.g. 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.

Upvotes: 13

Related Questions