[英]Insert an `int` value into a `std::map`, which is supposed to store `std::string`
I just had the following case: 我刚遇到以下情况:
std::map< int, std::string > mm;
mm[ 1 ] = 5;
std::cout << mm[1];
assert( mm.find( 1 ) != mm.end() );
This does NOT print anything and the assert
does NOT fail. 这不打印任何东西和assert
不会失败。
It appeared to be a typo, it must be mm[ 1 ] = '5';
它似乎是一个错字,它必须是mm[ 1 ] = '5';
. 。 After I figured it out, I tried: 在我弄明白之后,我尝试了:
std::string s1( 5 );
std::string s2 = 5;
None if this compiles. 没有,如果这编译。 What happens? 怎么了?
std::map::operator[]
first creates an element with type std::map::mapped_type
, then returns a reference to it. std::map::operator[]
首先创建一个类型为std::map::mapped_type
,然后返回对该元素的引用。
So, what happens here is the following: 因此,这里发生的是以下情况:
std::string
object is created and default-constructed; std::string
对象已创建并默认构造; std::map
创建的对象将插入到std::map
operator=
is called on this object 在此对象上调用operator=
In this case, std::string::operator=
is called. 在这种情况下,调用std::string::operator=
。
And here comes the "magic" - there's an overloaded operator=
, taking char
as argument. 这里出现了“魔术” - 有一个重载的operator=
,以char
为参数。 Also, the number can be implicitly converted to char
. 同样,该数字可以隐式转换为char
。 So, what actually happens is: 那么, 实际发生的是:
std::string s;
s = (char)5;
For example, this: 例如,这个:
mm[ 1 ] = 65; // ASCII for 'A'
mm[ 2 ] = 98; // ASCII for 'b'
std::cout << m[ 11 ] << mm[ 2 ];
will print Ab
. 将打印Ab
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.