使用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/