loopsc++11iteratorranged-loops

Whats the difference between these two range based loops


int main()
{             
       map<float,float>m;
       //input some value in m
        for(auto it=m.end();it!=m.begin();it--)
        {
           cout<<it.first<<" "<<it.second;
           
        }
    
    return 0;
}

The above code is not working now if instead of the above code I use the code below, its working perfectly fine. Idk why is it happening please tell me what is the difference.

int main()
{             
       map<float,float>m;
       //Input some value in m
        for(auto it:m)
        {
           cout<<it.first<<" "<<it.second;
        }

    return 0;
}

Solution

  •  map<float , float> m;
     auto it=m.end(); // here m.end() will return a pointer of after the last element
     it--; //now this points the last element
     for(;it!=m.begin();it--)
     {   
       cout<<it->first<<" "<<it->second<<"\n"
       cout<< (*it).first<<" " <<(*it).second<<"\n"
     }
     // this for the first element because m.begin() points to the first element
     cout<<it->first<<" "<<it->second<<"\n"
     cout<< (*it).first<<" " <<(*it).second<<"\n"
    

    here our it variable is of pointer type which points to the map element that's why need to use dereference () operators. An interesting property of pointers is that they can be used to access the variable they point to directly. This is done by preceding the pointer name with the dereference operator (). The operator itself can be read as "value pointed to by".

    while in the other case

       map<float,float>m;
       //Input some value in m
        for(auto it:m)
        {
           cout<<it.first<<" "<<it.second;
        }
        // we can also write it as 
        for(pair<float,float> it : m)
        {
           cout<<it.first<<" "<<it.second;
        }
    

    in this case we create a variable of pair type which copy the map value in it which can be access by (.) operator. the important thing to note is in the first case we are accessing by pointers and here we copy the map variable and then accessing it.so if we change our value using it variable then the change reflects in actual map also, but in second case any changes does affect our actual map .

    you can also use reverse iterator like this

       map<float,float>m;
       //input some value in m
        for(auto it=m.rbegin();it!=m.rend();it++)
        {
           count<<it->first<<" "<<it->second;
           
        }
    

    http://www.cplusplus.com/reference/map/map/begin/ here you will get more detail regarding this