Reputation: 2753
I would like to try inserting an element into the map with key k and value v. If the key is already present, I want to increment the value of that key.
Example,
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++;
}
This does not work. How can I do this?
Upvotes: 1
Views: 4847
Reputation: 27525
unordered_map:
Some beautiful code (variable names simplified):
From here 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";
}
Upvotes: 1
Reputation: 147054
You don't need iterators to achieve this goal. Because your v
is V() + 1
, then you can simply increment without needing to know whether or not the key was already present in the map.
mymap["a"]++;
This will do fine in your given example.
Upvotes: 4