In C++, std::unordered_map::max_size() returns the largest number of pairs an unordered_map of this type could possibly hold. It is a limit set by the library and the size of one node.
The number is usually enormous, so you will rarely reach it. A real program runs out of memory long before. It is mostly useful for generic code and for learning how containers work. 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 max_size with empty brackets. It returns an unsigned number.
Returns the maximum number of elements the unordered_map could hold, as size_type.
max_size() and size() answer different questions. size() is how many pairs you have now. max_size() is how many the type allows in theory. The exact value is implementation-defined, so never print it in a test and expect the same number everywhere.
Library declarations
C++
size_type max_size() const noexcept;
Parameters
Parameter
Description
None
max_size() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
size_type
The theoretical upper limit on the number of pairs. It does not tell you how much memory is free.
C++ Examples
Example 1 — max_size() Is Larger Than size()
Show that the limit is always at least as big as the number of pairs in the unordered_map.
addIfRoom() compares size() with max_size(). If the unordered_map were full it would return false and skip the insert.
The unordered_map is almost empty, so both checks pass and both calls insert a pair and return true.
In real programs this guard never fails. It only shows how max_size() is used as an upper bound, so the final size is 2.
Frequently Asked Questions
The largest number of pairs an unordered_map of that type could theoretically hold. It is a limit of the library and the node size, not of the free memory.
No. Your computer will run out of memory long before that number. If it does, insert() throws std::bad_alloc.
It is computed from the largest memory block the allocator could give, divided by the size of one node. On a 64-bit system that is a number in the billions or more.
No. The value is implementation-defined, so it can differ between compilers and platforms. Do not hard-code it.
size() is the number of pairs in the unordered_map now. max_size() is the most the type could ever hold in theory.