Skip to content
Related Articles

Related Articles

unordered_set rehash() function in C++ STL
  • Difficulty Level : Basic
  • Last Updated : 28 Sep, 2018

The unordered_set::rehash() is a built-in function in C++ STL which is used to set the number of buckets in the container of unordered_set to given size or more. If size is greater than the current size of the container, then rehash is called. If it is lower than the current size, then the function has no effect on bucket count of hash.

Syntax:

unordered_set_name.rehash(size_type n)

Parameter: The function accepts a mandatory parameter n which specifies the minimum number of buckets for the container.

Return Value: This function doesn’t returns anything.

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



Program 1:




// C++ program to illustrate the
// unordered_set::rehash()
#include <iostream>
#include <string>
#include <unordered_set>
  
using namespace std;
  
int main()
{
    // declaration
    unordered_set<string> us;
  
    // rehashed
    us.rehash(9);
  
    // insert elements
    us.insert("geeks");
    us.insert("for");
    us.insert("geeks");
    us.insert("users");
  
    for (auto it = us.begin(); it != us.end(); it++) {
        cout << *it << " ";
    }
  
    cout << "\nThe bucket count is "
         << us.bucket_count();
  
    return 0;
}
Output:
users for geeks 
The bucket count is 11

Program 2:




// C++ program to illustrate the
// unordered_set::rehash()
#include <iostream>
#include <string>
#include <unordered_set>
  
using namespace std;
  
int main()
{
    // declaration
    unordered_set<string> us;
  
    // rehash the unordered_set
    us.rehash(20);
  
    // insert strings
    us.insert("geeks");
    us.insert("for");
    us.insert("geeks");
    us.insert("users");
    us.insert("are");
    us.insert("experts");
    us.insert("in");
    us.insert("DS");
  
    // prints the elements
    for (auto it = us.begin(); it != us.end(); it++) {
        cout << *it << " ";
    }
  
    cout << "\nThe bucket count is "
         << us.bucket_count();
  
    return 0;
}
Output:
DS in experts are users for geeks 
The bucket count is 23
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :