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类型的
http://www.cplusplus.com/reference/stl/map/
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/
相关文章推荐
- error C2440: 'initializing' : cannot convert from 'boost::filesystem3::path' to 'std::basic_string<_
- Convert asio::streambuf to std::string
- C# Convert.ToString() 和 .ToString()的区别
- php 长整型转字符串 (convert long to string)
- Convert a string to a byte array and vica-versa in C#
- Convert a List to a Comma-Separated String in Java 8
- ToString()、Convert.ToString()、(string)、as string 的区别
- convert a byte array to a hexadecimal string
- Convert a string to an enum
- svn: Can't convert string from 'UTF-8' to native encoding
- How to convert XML String into XML document
- Implement atoi to convert a string to an integer.
- Convert string to int in C++
- Convert a String to a Number
- 【Z一贴】C++ String: How to convert a string into a numeric type?
- Failed to convert from type java.lang.String to type java.util.Date for value解决办法
- LeetCode Problem:String to Integer (atoi)
- Convert int to string
- Java——Read/convert an InputStream to a String
- Convert String to MM/dd/yyyy