C++ auto遍历无法直接修改map的数据

在C++中,使用for(autoit:myMap)对std::map进行范围循环时,由于使用的是const迭代器,所以不能直接修改map的值。要修改map的值,可以使用引用类型的迭代器如auto&it,或者采用传统的迭代器方式,如map::iteratorit=mp.begin()等。
摘要由CSDN通过智能技术生成

对于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
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值