c++ 自动,错误:Map迭代器没有名为“first”的成员

um6iljoc  于 2022-12-20  发布在  其他
关注(0)|答案(1)|浏览(371)
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;

为什么它不工作?

tkclm6bt

tkclm6bt1#

迭代器类似于指针,必须解引用才能用途:

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

ranged-for循环(auto示例)为您完成了这一任务。

相关问题