Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

range based for loop vs regular iterator for loop

Tags:

c++

loops

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.

like image 428
Abhinav Gauniyal Avatar asked Apr 11 '15 13:04

Abhinav Gauniyal


1 Answers

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.

like image 154
Arnošt Löbel Avatar answered Oct 13 '22 19:10

Arnošt Löbel