0

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));
    }
}

2 Answers2

2

Since there are only 256 possible values for a char, a better way is:

std::array<int, 256> probs;
probs.fill(0);
for (char ch : text)
    ++probs[ch];

The loop code is actually the same if you use unordered_map, but the above is more efficient.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
2

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;
}
alex_noname
  • 26,459
  • 5
  • 69
  • 86