public member function
<unordered_map>

std::unordered_multimap::rehash

void rehash( size_type n );
Set number of buckets
Sets the number of buckets in the container to n or more.

If n is greater than the current number of buckets in the container (bucket_count), a rehash is forced. The new bucket count can either be equal or greater than n.

If n is lower than the current number of buckets in the container (bucket_count), the function may have no effect on the bucket count and may not force a rehash.

A rehash is the reconstruction of the hash table: All the elements in the container are rearranged according to their hash value into the new set of buckets. This may alter the order of the elements within the container, although the relative order of the elements with equivalent keys is preserved.

Rehashes are automatically performed by the container whenever its load factor is going to surpass its max_load_factor in an operation.

Notice that this function expects the number of buckets as argument. A similar function exists, unordered_multimap::reserve, that expects the number of elements in the container as argument.

Parameters

n
The minimum number of buckets for the container hash table.
Member type size_type is an unsigned integral type.

Return value

none

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// unordered_multimap::max_load_factor
#include <iostream>
#include <string>
#include <unordered_map>

int main ()
{

  std::unordered_multimap<std::string,std::string> myumm;

  myumm.rehash(20);

  myumm.insert({{"apple","NY"},{"apple","WA"},{"peach","GA"}});
  myumm.insert({{"orange","FL"},{"cherry","UT"}});
  myumm.insert({{"strawberry","LA"},{"strawberry","NC"}});

  std::cout << "current bucket_count: " << myumm.bucket_count() << std::endl;

  return 0;
}


Possible output:
current bucket_count: 23

By calling rehash to reserve a certain minimum amount of buckets in the hash table, we avoid the multiple rehashes that the expansion of the container may cause.

Complexity

In case of rehash,
Average case: linear in container size.
Worst case: quadratic in container size.

Iterator validity

If a rehash happens, all iterators are invalidated, but references and pointers to individual elements remain valid.
If no actual rehash happens, no changes.

See also