簡體   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