Convert iterator to string ref problem

使用map等容器发现将迭代器转成string对象,会报错:

error C2440: 'initializing' : cannot convert from 'const class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' to 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > &'

可以知道,在类似如下定义的map容器中

map <string, int> mapStringKey;

key(string)在内部是被转化为const string存储的

string& strKey = itr->first;

就会遇到报错的情况,

正确的赋值方式如下:

1,string strKey = itr->first;

2,const string& strKey = itr->first;

===============================================

关于这点可以从如下文章中,可以看出一点端倪,map的定义的分配器中的key类型,就是const类型的

template < class Key, class T, class Compare = less<Key>,
           class Allocator = allocator<pair<const Key,T> > > class map;

http://www.cplusplus.com/reference/stl/map/

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值