public member function
<unordered_set>

std::unordered_set::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.

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_set::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
21
// unordered_set::rehash
#include <iostream>
#include <string>
#include <unordered_set>

int main ()
{
  std::unordered_set<std::string> myset;

  myset.rehash(12);

  myset.insert("office");
  myset.insert("house");
  myset.insert("gym");
  myset.insert("parking");
  myset.insert("highway");

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

  return 0;
}


Possible output:
current bucket_count: 13

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