问题描述
第一个是:
map <int,int> m;
//... some elements inserted
auto i= m.begin();
cout<<(*i).first<<(*i).second;
这里我们需要使用解引用操作符*
第二:
map <int,int> m;
//... some elements inserted
for(auto i: m)
cout<<i.first<<i.second;
为什么我这次不需要使用 * 运算符?
还有一个疑问:
for(auto &i: m)
“&”在这里有什么区别?
解决方法
auto i=m.begin()
会给你迭代器 .. 当你想访问值时,它更像是一个指针(语法上)访问......
for(auto i:m)
会将 m
的当前元素(一对)复制到 i
中,i
是元素的副本,而不是元素本身...
for (auto &i: m)
将在参考上工作,原始地图受到影响
如以下代码片段所述,第一个 i
是迭代器类型,而 for 循环中的 i
是 pair 类型。
#include <iostream>
#include <map>
int main()
{
std::map <int,int> m;
m[1] = 5;
m[10] = 60;
m[100] = 800;
// Below i is map iterator (std::map<int,int>::iterator)
auto i = m.begin();
std::cout << typeid(i).name() << '\n';
std::cout << (*i).first << " : " << (*i).second << '\n';
std::cout << i->first << " : " << i->second << '\n';
for(auto i: m) {
// Below i is pair<int,int>
std::cout << typeid(i).name() << '\n';
std::cout << i.first << " : " << i.second << '\n';
}
for(auto& i: m) {
// Below i is reference of pair<int,int>)
// modifying this would result in updated values in the map.
std::cout << typeid(i).name() << '\n';
std::cout << i.first << " : " << i.second << '\n';
}
return 0;
}