簡體   English   中英

我可以在不先找到 std map 的情況下更改它的值嗎

[英]Can i change the value of std map without finding it first

這就是我目前如何更改 std::map 的值

std::map<std::string, int> stdmapMasks;
stdmapMasks.insert(std::make_pair("VALUE", 1));
std::map<std::string, int>::iterator it = stdmapMasks.find('VALUE'); 
if (it != stdmapMasks.end())
    it->second = 42;

我可以直接更改值而無需查找地圖元素嗎?

C++ 有很多方法可以在不顯式調用map::find情況下與地圖的值進行交互。 operator[]允許您訪問一個值,如果它不存在,則默認構造它。 C++17 中的insert_or_assign提供了一種方法來做operator[]所做的事情,除了具有默認構造函數的要求。 如果鍵不存在,C++17 的try_emplacetry_emplace -construct 值,但如果那里已經有值,則不執行任何操作。

但是沒有任何版本的 C++ 有像“try_assign”這樣的方法,如果鍵已經存在,則不會發生賦值。 因此,您必須首先明確找到它。

暫無
暫無

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

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