unordered_set reserve() function in C++ STL

The unordered_set::reserve() method is a builtin function in C++ STL which is used to request capacity change of unordered_set. It sets the number of buckets in the container 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 the bucket_count, then the function has no effect on it.

Syntax:

unordered_set_name.reserve(size_type n)

Parameter: The function accepts a single mandatory parameter n which sets the number of buckets in the container (bucket_count) to the most appropriate to contain at least n elements.

Return Value: This function doesn’t returns anything.

Below programs illustrate the unordered_set::reserve() function:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to illustrate
// the unordered_set.reserve()
#include <iostream>
#include <string>
#include <unordered_set>
  
using namespace std;
  
int main()
{
    // Declaration of unordered_set
    unordered_set<string> us;
  
    us.reserve(3);
  
    us.insert("geeks");
    us.insert("for");
    us.insert("geeks");
    us.insert("users");
    us.insert("geeksforgeeks");
  
    for (auto it = us.begin(); it != us.end(); it++) {
        cout << *it << " ";
    }
  
    return 0;
}

chevron_right


Output:

geeksforgeeks users geeks for

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to illustrate
// the unordered_set.reserve()
#include <iostream>
#include <string>
#include <unordered_set>
  
using namespace std;
  
int main()
{
    // Declaration of unordered_set
    unordered_set<string> us;
  
    us.reserve(0);
  
    us.insert("geeks");
    us.insert("for");
    us.insert("geeks");
  
    for (auto it = us.begin(); it != us.end(); it++) {
        cout << *it << " ";
    }
  
    return 0;
}

chevron_right


Output:

for geeks


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.