简体   繁体   English

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

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

This is how currently i am changing the value of std::map这就是我目前如何更改 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;

Can i change the value directly without the need to find the map element ?我可以直接更改值而无需查找地图元素吗?

C++ has many ways to interact with a map's values without explicitly calling map::find . C++ 有很多方法可以在不显式调用map::find情况下与地图的值进行交互。 operator[] allows you to access a value, default constructing it if it does not exist. operator[]允许您访问一个值,如果它不存在,则默认构造它。 insert_or_assign from C++17 provides a way to do what operator[] does, save for the requirement of having a default constructor. C++17 中的insert_or_assign提供了一种方法来做operator[]所做的事情,除了具有默认构造函数的要求。 C++17's try_emplace will emplace-construct the value if the key is not present, but does nothing if there is already a value there.如果键不存在,C++17 的try_emplacetry_emplace -construct 值,但如果那里已经有值,则不执行任何操作。

But no version of C++ has a method like "try_assign", where assignment doesn't happen if the key already exists.但是没有任何版本的 C++ 有像“try_assign”这样的方法,如果键已经存在,则不会发生赋值。 So you will have to explicitly find it first.因此,您必须首先明确找到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM