問題描述
map<string, string> dada;
dada["dummy"] = "papy";
cout << dada["pootoo"];
我很困惑,因為我不知道它是否被認為是未定義的行為,如何知道我何時請求不存在的密鑰,我是否只使用 find ?
I'm puzzled because I don't know if it's considered undefined behaviour or not, how to know when I request a key which does not exist, do I just use find instead ?
推薦答案
map::operator[]
在數(shù)據(jù)結(jié)構(gòu)中搜索與給定鍵對應(yīng)的值,并返回對它的引用.
The map::operator[]
searches the data structure for a value corresponding to the given key, and returns a reference to it.
如果它找不到一個,它會透明地為它創(chuàng)建一個默認的構(gòu)造元素.(如果您不想要這種行為,您可以改用 map::at
函數(shù).)
If it can't find one it transparently creates a default constructed element for it. (If you do not want this behaviour you can use the map::at
function instead.)
您可以在此處獲取 std::map 方法的完整列表:
You can get a full list of methods of std::map here:
http://en.cppreference.com/w/cpp/container/map
這是當前 C++ 標準中 map::operator[]
的文檔...
Here is the documentation of map::operator[]
from the current C++ standard...
效果:如果映射中沒有與 x 等效的鍵,則將 value_type(x, T()) 插入映射中.
Effects: If there is no key equivalent to x in the map, inserts value_type(x, T()) into the map.
要求:key_type 應(yīng)為 CopyConstructible,mapped_type 應(yīng)為 DefaultConstructible.
Requires: key_type shall be CopyConstructible and mapped_type shall be DefaultConstructible.
返回:對 *this 中 x 對應(yīng)的映射類型的引用.
Returns: A reference to the mapped_type corresponding to x in *this.
復(fù)雜度:對數(shù).
T&運算符[](key_type&& x);
效果:如果映射中沒有與 x 等效的鍵,則將 value_type(std::move(x), T()) 插入映射中.
Effects: If there is no key equivalent to x in the map, inserts value_type(std::move(x), T()) into the map.
要求:mapped_type 應(yīng)為 DefaultConstructible.
Requires: mapped_type shall be DefaultConstructible.
返回:對 *this 中 x 對應(yīng)的映射類型的引用.
Returns: A reference to the mapped_type corresponding to x in *this.
復(fù)雜度:對數(shù).
這篇關(guān)于如果我在鍵不存在的情況下讀取地圖的值會發(fā)生什么?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!