0

Using the below C++ code prints different sizes of map before and after comparison.

#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
    string str1 = "abc", str2 = "def";
    map<char, int> mp;
    for(char c: str1) mp[c]++;
    cout << "Size of map: " << mp.size() << endl;
    for(char ch: str2) {
        if(mp[ch]) {
            // do something...
        }
    }
    cout << "Size of map: " << mp.size() << endl;
    return 0;
}

Why does checking whether a key exists in a map increases the size of the map?

Biswajit Roy
  • 508
  • 2
  • 7
  • 19
  • 1
    If you isolated your comparison into a function that takes a map by `const&`, you'd get a [compilation error](https://godbolt.org/z/c63jdj) instead of a silent bug. – Evg Jan 10 '21 at 08:03

1 Answers1

3
if(mp[ch])

This will call the map::operator[] with key ch.

If key matches to an element in map it will return the value of that element. If key does not match to any element in the map, the function inserts a new element with that key and returns a reference to its mapped value.

You can use map::find to check if the key is present or not in the map.

The Philomath
  • 954
  • 9
  • 15