Search code examples
c++for-loopiteratormapsauto

Two instances of keyword auto in cpp


First one being:

map <int,int> m;
//... some elements inserted
auto i= m.begin();
cout<<(*i).first<<(*i).second;

Here we are required to use the dereference operator *
Second:

map <int,int> m;
//... some elements inserted
for(auto i: m)
cout<<i.first<<i.second;

Why am I not required to use the * operator this time?
One more doubt:

for(auto &i: m)

what difference does '&' make here?


Solution

  • auto i=m.begin() will give you iterator .. which is accessed more like a pointer (syntactically) when you want to access the value...

    for(auto i:m) will copy current element of m (a pair) into i , i is a copy of element, not the element itself...

    for (auto &i: m) will work on a reference, the original map is affected