C++ unordered_map::get_allocator() 函式



C++ 的 std::unordered_map::get_allocator() 函式用於獲取與無序對映關聯的分配器的副本。分配器負責為儲存在無序對映中的元素分配和釋放記憶體。

此函式不會修改無序對映,也不會丟擲任何異常。

語法

以下是 std::unordered_map::get_allocator() 函式的語法。

allocator_type get_allocator() const;

引數

此函式不接受任何引數。

返回值

此函式返回一個分配器物件。

示例 1

在下面的示例中,我們演示了 get_allocator() 函式的用法。

#include <iostream>
#include <unordered_map>
using namespace std;
int main(void) {
   unordered_map<char, int> um;
   pair<const char, int> *p;
   p = um.get_allocator().allocate(5);
   cout << "Allocated size = " <<  sizeof(*p) * 5 << endl;
   return 0;
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

Allocated size = 40

示例 2

考慮以下示例,我們宣告一個無序對映物件並使用 get_allocator() 函式為無序對映分配對。如果分配了對,則返回 true;否則,返回 false。

#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;
int main() {
   unordered_map<int, int> uMap;
   unordered_map<int, int>::allocator_type umap = uMap.get_allocator();
   cout << "Is allocator Pair<int, int> : "<< boolalpha <<(umap == allocator<pair<int, int> >());
   return 0;
}

輸出

如果我們執行上述程式碼,它將生成以下輸出:

Is allocator Pair<int, int> : true
廣告