map<string, int> M;
for (auto E: M)
{
cout << E.first << ": " << E.second << endl;
F << E.first << ": " << E.second << endl;
};
我正在学习c ++而且我对auto很困惑。我试图将上面的代码转换为以下代码(上面的代码与auto正常工作)
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;
}
我收到以下错误:
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;
为什么它不起作用?
答案 0 :(得分:2)
迭代器就像指针一样,必须取消引用才能使用:
cout << p->first << ": " << p->second << endl;
ranged for for循环(带auto
的示例)为你做了这个。
当然,您的书会教您如何使用迭代器。