繁体   English   中英

在`std :: map`中插入一个`int`值,该值应该存储`std :: string`

[英]Insert an `int` value into a `std::map`, which is supposed to store `std::string`

我刚遇到以下情况:

std::map< int, std::string > mm;
mm[ 1 ] = 5;
std::cout << mm[1];
assert( mm.find( 1 ) != mm.end() );

打印任何东西和assert 不会失败。

它似乎是一个错字,它必须是mm[ 1 ] = '5'; 在我弄明白之后,我尝试了:

std::string s1( 5 );
std::string s2 = 5;

没有,如果这编译。 怎么了?

std::map::operator[]首先创建一个类型为std::map::mapped_type ,然后返回对该元素的引用。

因此,这里发生的是以下情况:

  1. std::string对象已创建并默认构造;
  2. 创建的对象将插入到std::map
  3. 返回对inserted元素的引用
  4. 在此对象上调用operator=

在这种情况下,调用std::string::operator=

这里出现了“魔术” - 有一个重载的operator= ,以char为参数。 同样,该数字可以隐式转换为char 那么, 实际发生的是:

std::string s;
s = (char)5;

例如,这个:

mm[ 1 ] = 65; // ASCII for 'A'
mm[ 2 ] = 98; // ASCII for 'b'
std::cout << m[ 11 ] << mm[ 2 ];

将打印Ab

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM