gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:25:23 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com