2

Suppose I have the following function:

  bool canConstruct(string ransomNote, string magazine) {
    unordered_map<char, int> map(26);
    for (int i = 0; i < magazine.size(); ++i)
        ++map[magazine[i]];
    for (int j = 0; j < ransomNote.size(); ++j)
        if (--map[ransomNote[j]] < 0)
            return false;
    return true;
}

Now supposedly if ransomNote has an element which does not exist in the map, I understand by reading the documentation and the question:

What happens if I read a map's value where the key does not exist?

A new default key is constructed having the value ' '. Now while referencing the key in second for loop, how is the value initialized to be zero?

How does the change in value corresponding to the key happen?

Is there any documentation for the same?

user0042
  • 7,917
  • 3
  • 24
  • 39
  • 1
    _"how is the value initialized to be zero?"_ Remember that `char` is a numeric type with values ranging from 0 - 255. – user0042 Jul 16 '17 at 14:26
  • 2
    @user0042 Or -128 to 127. Or -127 to 128 (depending on the underlying hardware). Remember that it's *implementation specified* if a `char` is `signed` or `unsigned`. – Some programmer dude Jul 16 '17 at 14:32

2 Answers2

3

A new default key is constructed having the value ' '.

No, that's wrong. The "default" value for a char is 0, as for any other integer numeric type.


Is there any documentation for the same?

The behavior of the std::map::operator[] is documented in detail here.

user0042
  • 7,917
  • 3
  • 24
  • 39
  • However if i print the value,before the second loop I get the output as blank . If,its initialized to zero how does that happen? – Varun Manocha Jul 16 '17 at 14:45
  • @VarunManocha _"I get the output as blank"_ Are you sure it's a blank? Try outputting the numbers as recommended [here](https://stackoverflow.com/questions/19562103/uint8-t-cant-be-printed-with-cout/19562163#19562163). I'm pretty sure it's not 32 (which is the ASCII code for `' '`). – user0042 Jul 16 '17 at 14:47
  • Allright I tried and got the value zero.I guess this is NULL and not blank right ? – Varun Manocha Jul 16 '17 at 14:52
  • @VarunManocha No, `NULL` is something different. It's simply zero (`0`) as mentioned. – user0042 Jul 16 '17 at 14:54
3

If you read e.g. this operator[] reference you will see that it basically creates the data element as T(). That is called value initialization, which for integer types like char means it will be initialized to zero.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621