C++ Counting occurrences using MAP (STL)














































C++ Counting occurrences using MAP (STL)



Counting occurrences

We may be doing many projects where there is a need for making count of occurrences. By using the map in STL library we can make count of different characters or values in a string or stream. It is just like using the dictionary in python.

We have map and unordered_map. map is a self balancing BST, while unordered_map is a hash table. Both these internal structures have their own pros and cons, so you have to choose which you want depending on the data you have

EXAMPLE:

#include <iostream>
#include <map>
#include <unordered_map>
using namespace std;

int main()
{
    string str = "cppsecrets is the best website for learning c++";

    // unordered_map<char, int> counter; // This is unordered_map
    map<charint> counter;

    for (char i : str)
        if (i != ' ') // Counts all charachters other than white spaces.
            counter[i]++;

    
    for (auto i : counter)
        cout << i.first << " : " << i.second << "\n"; // Accessing map elements

    return 0;
}

OUTPUT:

+ : 2
a : 1
b : 2
c : 3
e : 7
f : 1
g : 1
h : 1
i : 3
l : 1
n : 2
o : 1
p : 2
r : 3
s : 5
t : 4
w : 1

Comments