c++ - 自动,错误 : map iterator has no member named ‘first`

标签 c++ iterator

map<string, int> M;
for (auto E: M) 
{ 
    cout << E.first << ": " << E.second << endl; 
    F << E.first << ": " << E.second << endl; 
}; 

我正在学习 c++,但我对 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;

为什么它不起作用?

最佳答案

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

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

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

关于c++ - 自动,错误 : map iterator has no member named ‘first` ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44251704/

相关文章:

hostname - 写一个C++代码来获取主机名

java - 接口(interface)的更高级用法

java - 在内部类中调用此实例

c++ - 征求关于自定义迭代器的建议我在 C++ 中自定义的容器

c++ - 在 C++ 中实现全局应用程序设置

c++ - 独立的 C++ 编译器

c++ - qt工程文件库包括

c++ - 有没有办法在 Python 中执行 "template base class"?

c++ - 函数中输出容器默认值的开始

c++ - 看不懂迭代器的问题?