for(auto it = M.begin(); it!=M.end();it++)
{
cout<<it->first<<" "<<it->second<<"\n";
}
The above code works absolutely fine But,
for(auto it : M)
{
if(it->second == 1) return it->first;
}
This gives me an error.
Why do I have to use it.second
and it.first
instead of it->second
and it->first
?
In the first loop, you use iterators to iterate over the container M
. Iterators emulate pointers, and have to be dereferenced to give the value the iterator is "pointing" at. In fact, for that loop, it->first
is really the same as (*it).first
.
In the second loop, you loop over the values in the container M
. The loop itself uses iterators internally and dereferences them for you. This reference about "range-based for
loops" might help you.