question about range for loops

i wonder is

1
2
3
  for(auto i:{0, 1, 2, 3, 4, 5}){
      cout << i << endl;
  }


technically and syntactically identical to

1
2
3
4
vector<int> v{0, 1, 2, 3, 4, 5};
for(auto i = v.begin(); i != v.end(); i++){
      cout << *i << endl;
  }


and why in the first sample, cout << i outputs correctly while cout << *i doesn't?
thanks!
1. i is value
2. i is iterator
Yes, it is almost identical.
I think this might help: http://en.cppreference.com/w/cpp/language/range-for

and why in the first sample, cout << i outputs correctly while cout << *i doesn't?
Because range-based-for provides you values and not iterators to them. std:cout << *2 does not have any sense, does it?
> i wonder is
1
2
3
>  for(auto i:{0, 1, 2, 3, 4, 5}){
>      cout << i << endl;
>  }

> technically and syntactically identical to
1
2
3
4
> vector<int> v{0, 1, 2, 3, 4, 5};
> for(auto i = v.begin(); i != v.end(); i++){
>      cout << *i << endl;
>  }


No.

1
2
3
for(auto i:{0, 1, 2, 3, 4, 5}){
     cout << i << endl;
}

is semantically equivalent close to:
1
2
3
4
5
6
7
8
{
    // the underlying temporary array may be allocated in read-only memory.
    constexpr int temp[] = {0, 1, 2, 3, 4, 5}; 
    
    for( const int* iter = std::begin(temp) ; iter != std::end(temp) ; ++iter ) {
        int i = *iter ; // auto i => value semantics (operate on a copy)
        std::cout << i << std::endl ;
} // the underlying array is not guaranteed to exist after this 

See: http://en.cppreference.com/w/cpp/utility/initializer_list
Last edited on
simply,
int a =5;
cout<< a; // not cout << *a;

int *pt = &a;

cout << *pt; // to see 5. you know what cout << pt; would show.
Topic archived. No new replies allowed.