2012-03-28 324 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"; 
}