C++ Standard Library C++ STL Library

C++ unordered_multiset - reserve() Function



The C++ unordered_multiset::reserve function is used to request a capacity change in the unordered_multiset. It sets the number of buckets in the container such that the container contains at least specified number (n) of elements. If n is greater than the bucket_count multiplied by max_load_factor, the container's bucket_count is increased and a rehash is forced. If n is less than the bucket_count multiplied by max_load_factor, the function may have no effect. A rehash is the reconstruction of the hash table in which all elements of the container is rearranged according to their hash values into the new set of buckets.

As an unordered_multiset is implemented using hash table where a bucket is a slot in the container's internal hash table to which elements are assigned based on the hash value. The number of buckets directly influences the load_factor of the container's hash table. The container automatically increases the number of buckets to keep the load_factor below its max_load_factor which causes rehash whenever the number of buckets is increased.

Syntax

void reserve (size_type n);

Parameters

n Specify the number of elements requested as minimum capacity.

Return Value

None.

Time Complexity

Average case: Linear i.e, Θ(n).
Worst case: Quadratic i.e, Θ(n²).

Example:

In the example below, the unordered_multiset::reserve function is used to request a capacity change of uMSet container.

#include <iostream>
#include <unordered_set>
using namespace std;
 
int main (){
  unordered_multiset<int> uMSet{55, 25, 128, 55};

  cout<<"uMSet contains "<<uMSet.bucket_count()<<" buckets:";
  for(unsigned int i = 0; i < uMSet.bucket_count(); i++) {
    cout<<"\nThe bucket #"<<i<<" contains: ";   
    for(auto it = uMSet.begin(i); it != uMSet.end(i); ++it) {
      cout<<*it<<" ";
    } 
  }  

  cout<<"\n\nCapacity is changed using reserve function.\n\n";
  uMSet.reserve(10);

  cout<<"uMSet contains "<<uMSet.bucket_count()<<" buckets:";
  for(unsigned int i = 0; i < uMSet.bucket_count(); i++) {
    cout<<"\nThe bucket #"<<i<<" contains: ";   
    for(auto it = uMSet.begin(i); it != uMSet.end(i); ++it) {
      cout<<*it<<" ";
    } 
  }  

  return 0;
}

The output of the above code will be:

uMSet contains 5 buckets:
The bucket #0 contains: 25 55 55 
The bucket #1 contains: 
The bucket #2 contains: 
The bucket #3 contains: 128 
The bucket #4 contains: 

Capacity is changed using reserve function.

uMSet contains 11 buckets:
The bucket #0 contains: 55 55 
The bucket #1 contains: 
The bucket #2 contains: 
The bucket #3 contains: 25 
The bucket #4 contains: 
The bucket #5 contains: 
The bucket #6 contains: 
The bucket #7 contains: 128 
The bucket #8 contains: 
The bucket #9 contains: 
The bucket #10 contains: 

❮ C++ <unordered_set> Library