Increment map value associated with a key in C++
Given an ordered or an unordered map and a key in C++, increment the map value associated with that key.
The idea is to use the unordered_map::find
function that searches the container for a key and returns an iterator to it, or the unordered_map::end
if the key is not found.
Once the key is found, we can increment its value using the ++
operator on the second member function of the pair pointed by the iterator. If the key is not found, we can insert it into the map with value 1 using unordered_map::insert
with std::make_pair
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
#include <iostream> #include <unordered_map> #include <iterator> int main() { std::string s = "ABCBADCA"; std::unordered_map<char, int> freq; for (const char &c: s) { // check if key `c` exists in the map or not std::unordered_map<char, int>::iterator it = freq.find(c); // key already present on the map if (it != freq.end()) { it->second++; // increment map's value for key `c` } // key not found else { freq.insert(std::make_pair(c, 1)); } } for (auto &e: freq) { std::cout << '{' << e.first << ", " << e.second << '}' << std::endl; } return 0; } |
Output:
{D, 1}
{C, 2}
{B, 2}
{A, 3}
We can also use operator[]
, which makes this very easy. It returns a reference to the mapped value for the specified key. If the key does not exist in the map, it inserts a new pair with that key and the default value of 0
(for numeric data types) and returns a reference to it. Once we reference the mapped value of a key, we can use the ++
operator to increment its value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <unordered_map> int main() { std::unordered_map<char, int> freq; std::string s = "ABCBADCA"; for (const char &c: s) { freq[c]++; // increment map's value for key `c` } for (auto &e: freq) { std::cout << '{' << e.first << ", " << e.second << '}' << std::endl; } return 0; } |
Output:
{D, 1}
{C, 2}
{B, 2}
{A, 3}
That’s all about incrementing the map value associated with a key in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)