簡體   English   中英

如何僅通過鍵插入來初始化新的std :: map條目?

[英]How are new std::map entries initialized just by key insertion?

我有一個std::vector<MyString> ,該數據不是唯一的。 實際上,大多數字符串都是重復的。 而且我必須找到唯一的和重復的編號。

我使用地圖:

std::map<MyString,unsigned short> stringsMap;
.......
if ( stringsMap.find( currentString ) == stringsMap.end() )
{
    stringsMap[ currentString ] = 0;
}

stringsMap[ currentString ]++;
........

您有想法如何在更少的行上完成嗎?

可以在一行上完成: stringsMap[ currentString ]++; 但是short默認情況下具有不確定的值。

可以在一行上完成:stringsMap [currentString] ++; 但是short默認情況下具有不確定的值。

這是不正確的,價值的定義如文檔所述

如果執行插入操作,則將對映射的值進行值初始化(對於類類型,默認為默認構造, 否則為零初始化 ),並返回對其的引用。

重點是我的。

因此,寫一個襯紙是完全可以的:

stringsMap[ currentString ]++;

這是常見的做法,甚至在文檔中作為示例給出:

// count the number of occurrences of each word
// (the first call to operator[] initialized the counter with zero)
std::map<std::string, size_t>  word_map;
for (const auto &w : { "this", "sentence", "is", "not", "a", "sentence",
                       "this", "sentence", "is", "a", "hoax"}) {
    ++word_map[w];
}

但是short默認情況下具有不確定的值。

否。對於不存在的鍵,映射將使用T()初始化新創建的條目的值,對於unsigned short ,該條目的有效值為0

請參閱std::map::operator[]文檔 (強調我的1 ):

1)如果鍵不存在value_type(key, T())插入value_type(key, T()) 此函數等效於return insert(std::make_pair(key, T())).first->second;
- key_type必須滿足的要求, CopyConstructible
mapped_type必須滿足CopyConstructibleDefaultConstructible的要求。
如果執行插入操作,則將對映射的值進行值初始化(對於類類型,默認為默認構造, 否則為零初始化 ),並返回對其的引用。

因此,只寫

std::map<MyString,unsigned short> stringsMap;
.......
stringsMap[ currentString ]++;

很好。 整個if塊是多余的,不需要。


1) 這不是真的,這是@Remy Lebau的重點

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM