public member function
<unordered_map>

std::unordered_map::reserve

void reserve ( size_type n );
Request a capacity change
Sets the number of buckets in the container (bucket_count) to the most appropriate to contain at least n elements.

If n is greater than the current bucket_count multiplied by the max_load_factor, the container's bucket_count is increased and a rehash is forced.

If n is lower than that, the function may have no effect.

Parameters

n
The number of elements requested as minimum capacity.
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
23
24
// unordered_map::reserve
#include <iostream>
#include <string>
#include <unordered_map>

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

  mymap.reserve(6);

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

  for (auto& x: mymap) {
    std::cout << x.first << ": " << x.second << std::endl;
  }

  return 0;
}


Possible output:
book: livre
house: maison
grapefruit: pamplemousse
tree: arbre
apple: pomme
door: porte

By calling reserve with the size we expected for the unordered_map container we avoided the multiple rehashes that the increases in container size could have produced and optimized the size of the hash table.

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