简体   繁体   中英

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.

It appeared to be a typo, it must be 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.

So, what happens here is the following:

  1. std::string object is created and default-constructed;
  2. the created object is inserted into the std::map
  3. reference to the inserted element is returned
  4. operator= is called on this object

In this case, std::string::operator= is called.

And here comes the "magic" - there's an overloaded operator= , taking char as argument. Also, the number can be implicitly converted to 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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