auto, error: map iterator has no member named ‘first`

Viewed 16721
map<string, int> M;
for (auto E: M) 
{ 
    cout << E.first << ": " << E.second << endl; 
    F << E.first << ": " << E.second << endl; 
}; 

I am learning c++ and I am confused with auto. I am trying to convert the above code into the following code( the above code with auto works correctly)

map<string, int> M;
for (map<string, int> :: iterator p = begin(M); p != end(M); p ++ )
{
    cout << p.first << ": " << p.second << endl;
    F << p.first << ": " << p.second << endl;
}

I got the following error:

 error: ‘std::map<std::basic_string<char>, int>::iterator’ has no member named ‘first’
     cout << p.first << ": " << p.second << endl;
 error: ‘std::map<std::basic_string<char>, int>::iterator’ has no member named ‘second’
     cout << p.first << ": " << p.second << endl;
 error: ‘std::map<std::basic_string<char>, int>::iterator’ has no member named ‘first’
     F << p.first << ": " << p.second << endl;
 error: ‘std::map<std::basic_string<char>, int>::iterator’ has no member named ‘second’
     F << p.first << ": " << p.second << endl;

Why it does not work?

1 Answers
Related