C++ Unordered_set Library - reserve



Description

It sets the number of buckets in the container (bucket_count) to the most appropriate to contain at least n elements.

Declaration

Following is the declaration for std::unordered_set::reserve.

C++11

void reserve ( size_type n );

Parameters

n − n is the minimum number of buckets.

Return value

none

Exceptions

Exception is thrown if any element comparison object throws exception.

Please note that invalid arguments cause undefined behavior.

Time complexity

constant time.

Example

The following example shows the usage of std::unordered_set::reserve.

#include <iostream>
#include <string>
#include <unordered_set>

int main () {
   std::unordered_set<std::string> myset;

   myset.reserve(5);

   myset.insert("android");
   myset.insert("java");
   myset.insert("html");
   myset.insert("css");
   myset.insert("wordpress");

   std::cout << "myset contains:";
   for (const std::string& x: myset) std::cout << " " << x;
   std::cout << std::endl;

   return 0;
}

Let us compile and run the above program, this will produce the following result −

myset contains: wordpress android java html css
unordered_set.htm
Advertisements