unordered_set::reserve()方法是C++ STL中的内置函数,用于请求更改unordered_set的容量。它将容器中的存储桶数设置为至少包含n个元素。如果n大于当前的bucket_count乘以max_load_factor,则该容器的bucket_count会增加,并强制进行重新哈希处理。如果n小于bucket_count,则该函数对其无效。
用法:
unordered_set_name.reserve(size_type n)
参数:该函数接受单个强制性参数n,该参数将容器中的存储桶数(bucket_count)设置为最适合包含至少n个元素的桶数。
返回值:此函数不返回任何内容。
以下示例程序旨在说明unordered_set::reserve()函数:
示例1:
// 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; 
}
输出:
geeksforgeeks users geeks for
示例2:
// 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; 
}
输出:
for geeks
相关用法
- C++ unordered_multimap reserve()用法及代码示例
- C++ unordered_map reserve()用法及代码示例
- C++ unordered_multiset reserve()用法及代码示例
- C++ log()用法及代码示例
- C++ div()用法及代码示例
- C++ fma()用法及代码示例
- C++ wcsncpy()用法及代码示例
- C++ real()用法及代码示例
- C++ imag()用法及代码示例
注:本文由纯净天空筛选整理自barykrg大神的英文原创作品 unordered_set reserve() function in C++ STL。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
