如何修改unordered_map中的值?

时间:2012-03-28 02:12:01

标签: c++ visual-c++ c++11

我想尝试使用键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++;
} 

这不起作用。我怎么能这样做?

2 个答案:

答案 0 :(得分:3)

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

mymap["a"]++;

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

答案 1 :(得分:1)

unordered_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";
}
相关问题