簡體   English   中英

使用[]的C ++地圖插入

[英]C++ map insertion using []

我發現未找到密鑰時,下標運算符中的代碼對於std::map來說像這樣。 但是在這里,它們添加了默認值。

__i = insert(__i, value_type(__k, mapped_type()));

現在如果我這樣做

std::map<std::string,int> mapped;
mapped["current"] = 5;

我想知道如何使用上面的語句將這對添加到地圖上。

如果找不到地圖, operator[]插入地圖的元素,然后將其返回。

因此,參數鍵(__i)和值(__k)被添加到映射中。

這是一個STL實現:

_Tp& operator[](const key_type& k) { // k is the parameter you passed

    iterator i = lower_bound(k);

    // if i -> first >= k then insert a place for the new element.
   if (i == end() || key_comp()(k, (*i).first))
       i = insert(i, value_type(k, _Tp()));

    // return a reference to the element mapped to by the key
    return i -> second;
 }

由於返回了引用,因此其行為與訪問數組的行為完全相同:

您可以分配 ray[5] = 10訪問 int i = ray[5]

暫無
暫無

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

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