public member function
<unordered_map>

std::unordered_map::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 iteration of 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_map::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
22
// unordered_map::rehash
#include <iostream>
#include <string>
#include <unordered_map>

int main ()
{
  std::unordered_map<std::string,std::string> mymap;

  mymap.rehash(20);

  mymap["house"] = "maison";
  mymap["apple"] = "pomme";
  mymap["tree"] = "arbre";
  mymap["book"] = "livre";
  mymap["door"] = "porte";
  mymap["grapefruit"] = "pamplemousse";

  std::cout << "current bucket_count: " << mymap.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

  • 997351548 2018-02-20
  • 903691547 2018-02-20
  • 9127171546 2018-02-20
  • 2234751545 2018-02-20
  • 1685381544 2018-02-20
  • 911091543 2018-02-20
  • 9281021542 2018-02-20
  • 632231541 2018-02-20
  • 9751491540 2018-02-20
  • 8333621539 2018-02-20
  • 995001538 2018-02-20
  • 6477441537 2018-02-20
  • 511981536 2018-02-19
  • 2072881535 2018-02-19
  • 6024461534 2018-02-19
  • 7594061533 2018-02-19
  • 9311341532 2018-02-19
  • 4928331531 2018-02-19
  • 38561530 2018-02-19
  • 7776611529 2018-02-19