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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With