auto,错误:map iterator没有名为'first`的成员

时间:2017-05-30 00:14:56

标签: c++ iterator

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;

为什么它不起作用?

1 个答案:

答案 0 :(得分:2)

迭代器就像指针一样,必须取消引用才能使用:

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

ranged for for循环(带auto的示例)为你做了这个。

当然,您的书会教您如何使用迭代器。