Search code examples
c++dictionaryhashmap

Find number of occurrences in a map C++


I am trying to create a map in C++ and I will use it to compare wheater a vector of string match another one. The condition is that only one word can be taken into consideration. For example, given:

{"two", "times", "three", "is", "not", "four"}
{"two", "times", "two", "is", "four"}

In this case they shouldn't match because there is only one "two" in the first vector.

My code is as follows:

#include <iostream>
#include <vector>
#include <map>

using namespace std;

void checkMagazine(vector<string> magazineWords, vector<string> noteWords)
{
    map<string, int> magazine;
    map<string, int>::iterator it = magazine.begin();

    //populating the map
    for (string magazineWordString : magazineWords)
    {
        it = magazine.find(magazineWordString);

        if (it != magazine.end())
        {
            int numberOfOccurences = it->second;
            magazine.insert(pair<string, int>(magazineWordString, numberOfOccurences + 1));
        }
        else
        {
            magazine.insert(pair<string, int>(magazineWordString, 1));
        }
    }

    //checking for correspondences
    for (string noteWordString : noteWords)
    {
        it = magazine.find(noteWordString);

        if (it != magazine.end())
        {
            int numOfOccurences = it->second;
            magazine.insert(pair<string, int>(noteWordString, numOfOccurences - 1));
        }
        else
        {
            cout << "There is no match." << endl;
            return;
        }
    }

    cout << "There is a match!" << endl;
}

Solution

  • There's a far easier way! The subscript operator on a map will try to find the key in the map. If it is successful, it returns a reference to its value. Otherwise, it creates a new key/value pair for you on the spot and gives you a reference to its value.

    So since the default value of an int will be 0 (that is, when we create a new key/value pair, the value will be 0), all your work can actually just be:

    bool checkMagazine(vector<string> magazineWords, vector<string> noteWords)
    {
        map<string, int> bank;
    
        //populating the map
        for (string magazineWord : magazineWords) {
            ++bank[magazineWord];
        }
    
        //checking for correspondences
        for (string noteWord : noteWords) {
            if(--bank[noteWord] < 0) { return false; }
        }
    
        return true;
    }
    

    Watch it run here: https://ideone.com/MzLAJM