Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

iterator

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?

like image 527
chenyinuo Avatar asked Feb 05 '23 09:02

chenyinuo


1 Answers

Iterators are like pointers and must be dereferenced for use:

cout << p->first << ": " << p->second << endl;

The ranged-for loop (the example with auto) did this for you.

like image 114
Lightness Races in Orbit Avatar answered Feb 13 '23 17:02

Lightness Races in Orbit