Reputation: 2148
Couldn't find on stackoverflow.
std::map<T>.size()
gives number of elements, not keys.
So how to get the number of keys?
Upvotes: 4
Views: 23010
Reputation: 36
Since the keys are not repeated in a map, the size gives the number of keys in the map.
Extra knowledge:- In the datatype multimap, the keys can be repeated, and over there the number of keys will not be equal to the size of the map as in the case of simple maps.
Upvotes: 2
Reputation: 117298
std::map<T>.size()
Gives the number of elements, and keys. It's a 1-to-1 match.
A map
has a union of all keys you've tried to insert into the map. Insertion of an already existing key will be rejected if done via insert
/emplace
but the value-mapping will be replaced if the insertion is done using operator[]
.
In a map a key can only map to one value. It's a dictionary.
Variants:
There are multimap
(and multiset
) versions. In a multimap
multiple equal keys may map to different entities.
A -> foo
A -> apa
B -> bar
B -> bepa
In this multimap
the size would be 4
which is the number of mapped elements, not the number of unique keys (which isn't a concern for multimaps).
The size()
member function of a regular map
and a multimap
return the number of mapped elements, which for a regular map
is the same as the number of unique key values.
Upvotes: 14
Reputation:
The number of keys is equal to the number of elements in a map, for which its size would be the same.
Upvotes: 6