对于std::map
,当使用for (auto it : myMap)
这种范围循环形式时,实际上是使用了const
迭代器进行遍历。这意味着你无法通过该迭代器直接修改std::map
中的值。
范围循环使用的是容器的begin()
和end()
函数返回的迭代器,而对于std::map
,这些函数返回的是const
迭代器。因此,使用范围循环时,迭代器的类型会自动推导为const
迭代器,从而无法直接修改值。
如果你想要修改std::map
中的值,可以改用普通的迭代器形式,例如使用auto it =myMap.begin()
和it != myMap.end()
的迭代器循环,或者使用for (auto& pair : myMap)
形式的范围循环,并将迭代器声明为引用类型(auto&
)以允许修改值。
#include<bits/stdc++.h>
using namespace std;
int main(){
map<int,int>mp;
mp[1]=1;
mp[2]=2;
mp[3]=3;
cout<<"用auto直接修改:(无法修改)"<<endl;
for(auto it:mp){
it.second++;
}
for(auto it:mp){
cout<<it.first<<" "<<it.second<<endl;
}
cout<<"用&auto修改:"<<endl;
for(auto &it:mp){
it.second++;
}
for(auto it:mp){
cout<<it.first<<" "<<it.second<<endl;
}
cout<<"用普通迭代器修改:"<<endl;
for(map<int,int>::iterator it=mp.begin();it!=mp.end();it++){
it->second++;
}
for(auto it:mp){
cout<<it.first<<" "<<it.second<<endl;
}
return 0;
}
用auto直接修改:(无法修改)
1 1
2 2
3 3
用&auto修改:
1 2
2 3
3 4
用普通迭代器修改:
1 3
2 4
3 5