當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ unordered_set reserve()用法及代碼示例

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


相關用法


注:本文由純淨天空篩選整理自barykrg大神的英文原創作品 unordered_set reserve() function in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。