dimanche 22 avril 2018

Iterating through container - when to use reference and when not

In the code below, we don't dereference y (it is error in fact), but we do dereference z. Can someone explain why so?

 #include <iostream>  
 #include <vector>  


int main()   
{  
std::vector <int> x = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

 for( auto y : x ) 
     std::cout << y << " ";  

std::cout<<std::endl;

for(auto z = x.begin();z!=x.end();++z)
    std::cout<<*z<<" ";
}

Aucun commentaire:

Enregistrer un commentaire