在 C++ STL 中設定 get_allocator()
本文中,我們將討論 C++ STL 中的 set::get_allocator() 函式,它們語法、工作方式和返回值。
什麼是 C++ STL 中的 Set?
C++ STL 中的 Set 是容器,必須按照一般順序包含唯一元素。Set 必須包含唯一元素,因為元素的值會識別出該元素。一旦將值新增到 set 容器中,後來就不能修改,儘管我們仍然可以刪除或向 set 新增值。set 被用作二叉搜尋樹。
什麼是 set:: get_allocator()?
get_allocator() 函式是 C++ STL 中的一項內建函式,該函式在 <set> 標頭檔案中定義。該函式返回與之關聯的 set 容器的分配器物件的副本。get_allocator() 用於為 set 容器分配記憶體塊。
分配器是一種對 set 容器進行動態記憶體分配的物件。
語法
Set1.get_allocator();
引數
該函式不接受任何引數
返回值
該函式返回分配器或與該函式關聯的物件的分配器的副本。
示例
#include <iostream> #include <set> using namespace std; void input(int* arr){ for(int i = 0; i <= 5; i++) arr[i] = i; } void output(int* arr){ for (int i = 0; i <= 5; i++) cout << arr[i] << " "; cout << endl; } int main(){ set<int> mySet; int* arr; arr = mySet.get_allocator().allocate(6); input(arr); output(arr); mySet.get_allocator().deallocate(arr, 6); return 0; }
輸出
如果我們執行上述程式碼,它將生成以下輸出 −
0 1 2 3 4 5
廣告