2012-03-28 325 views
0

我想尝试使用键k和值v在地图中插入一个元素。如果键已经存在,我想增加该键的值。如何修改unorderedmap中的值?

例,

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++; 
} 

这是行不通的。我怎样才能做到这一点?

+1

你应该提供编译例子。否则,我们无法知道这些拼写错误是否确实是错误的。此外,你应该指定你的代码不工作的“如何”。 – mfontanini 2012-03-28 02:27:18

回答

2

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

mymap["a"]++; 

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

+0

我试过这个,但我发现它为相同的密钥插入另一个节点。 – 2012-03-28 02:29:24

+3

“同一个键的另一个节点” - >这是不可能的。一个关键,一个节点。如果不存在,它将插入* new *节点。 – 2012-03-28 02:38:13

0

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"; 
}