In C++, std::unordered_map::size() returns how many pairs the unordered_map holds right now. Each pair is one key together with its value.
Because every key in an unordered_map is unique, size() is also the number of distinct keys. That makes it handy for counting different words or ids. Include <unordered_map> to use it.
This is a member of std::unordered_map<Key, T>, a hash table of key and value pairs. Each key is unique. Find, insert, and erase are usually average constant time. Unlike std::map, keys are not sorted and iteration order is unspecified. Read a value with at() or find(). The m[key] operator also works, but it adds a default value when the key is missing.
Syntax
Call size with empty brackets. It returns an unsigned number.
C++
std::size_t n = m.size(); // number of pairs
if (m.size() >= 3) {
// the unordered_map has at least three pairs
}
Call
What it does
m.size()
Returns the number of elements as size_type, an unsigned integer type (usually std::size_t).
size() is not the same as count(key). size() counts all pairs. count(key) tells you whether one key exists, so it is only 0 or 1 for an unordered_map.
Library declarations
C++
size_type size() const noexcept;
Parameters
Parameter
Description
None
size() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
size_type
The number of key and value pairs in the unordered_map. It is 0 for an empty map.
C++ Examples
Example 1 — size() After Each Change
Print the size after an insert() and after an erase().