What is the difference between it.first and it->first?

Viewed 574
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?

2 Answers

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.

Basically you use . operator to access members of objects and it->first simply means (*it).first. So it is a pointer pointing to your variable which has a member first, so to access first, you just dereference the pointer then use . to access the member. Now if it was your variable instead of a pointer to the variable, then you could simply access its member first via it.first.

Related