Search code examples
c++variable-assignmentunordered-mapprobability-distribution

How do we assign variables and update them in unordered maps in C++?


I am trying to implement a probability distribution of characters in the text. I am trying to learn unordered maps, but I could not update the probs map after inserting the pair. Let's say we assigned letters 'a', 'b' and 'c', I want to increment the value of 'a' in the map. Any suggestions?

string text = "abcaa";
unordered_map<char, int> probs;
int i = 0;
//Initialize the probability map.
for (char& ch : text) {
    if (probs.find(ch) != probs.end()) //if ch not in probs, create a pair.
    {
        probs.insert(make_pair(ch, 1));
    }
}

Solution

  • You could write right away probs[ch]++.

    Because if ch does not match the key of any element in the container, the [] operator inserts a new element (constructed using its default constructor) with that key and returns a reference to its mapped value.

    int main() {
        std::string text = "abcaa";
        std::unordered_map<char, int> probs;
        int i = 0;
    
        for (char& ch : text)
            probs[ch]++;
    
        for (auto& it: probs)
            std::cout << it.first << " " << it.second << std::endl;
    }