Why map <bool, int> m = {{1,2}, {3,4}, {5,0}}; size 1, not 3?

Pretty strange:

map<bool,int> mb={{1,2},{3,4},{5,0}}; cout << mb.size(); map<int,int> mi={{1,2},{3,4},{5,0}}; cout << mi.size(); 

displays

thirteen

+5
source share
3 answers

std::map is a unique key. 1 , 3 , 5 all give true when converting to bool .

+18
source

Just suppose, but your first card has bool as the key type, and all values 1, 3 and 5 are evaluated as true.

You are only rewriting the same record.

+7
source

Your first card has a bool as a key. There are only two bool values. You enter ints as input. Non-0 ints are true, and 0 ints are false. Therefore, all your keys are correct. Two of them were overwritten last. That is why the size is 1.

+6
source

Source: https://habr.com/ru/post/1213666/


All Articles