您的位置:首页 > 其它

Convert iterator to string ref problem

2011-10-17 11:35 274 查看
使用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/

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息