如何修改无序映射中的值

How to modify value in unorderedmap?

本文关键字:映射 无序 何修改 修改      更新时间:2023-10-16

我想尝试将一个元素插入到具有键k和值v的映射中。如果该键已经存在,我想增加该键的值。

示例,

typedef std::unordered_map<std::string,int> MYMAP;
MYMAP mymap;
std::pair<MYMAP::iterator, bool> pa=  
    mymap.insert(MYMAP::value_type("a", 1));
if (!pa.second)
{
    pa.first->second++;
} 

这不起作用。我该怎么做?

您不需要迭代器来实现此目标。因为您的vV() + 1,所以您可以简单地递增,而无需知道密钥是否已经存在于映射中。

mymap["a"]++;

这在你给出的例子中会很好。

unordereded_map:

一些漂亮的代码(简化了变量名):
从这里http://en.cppreference.com/w/cpp/container/unordered_map/operator_at

std::unordered_map<char, int> mu1 {{'a', 27}, {'b', 3}, {'c', 1}}; 
mu1['b'] = 42;  // update an existing value
mu1['x'] = 9;   // insert a new value
for (const auto &pair: mu1) {
    std::cout << pair.first << ": " << pair.second << 'n';
}
// count the number of occurrences of each word
std::unordered_map<std::string, int> mu2;
for (const auto &w : { "this", "sentence", "is", "not", "a", "sentence", "this", "sentence", "is", "a", "hoax"}) {
    ++mu2[w];   // the first call to operator[] initialized the counter with zero
}
for (const auto &pair: mu2) {
    std::cout << pair.second << " occurrences of word '" << pair.first << "'n";
}