C++ unordered_multimap::get_allocator() 函式



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

此函式不會修改 unordered_multimap 並且不會丟擲任何異常。

語法

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

allocator_type get_allocator() const;

引數

此函式不接受任何引數。

返回值

此函式返回與 unordered_multimap 關聯的分配器。

示例 1

在以下示例中,讓我們看看 unordered_multimap::get_allocator() 函式的使用方法。

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

輸出

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

Allocated size = 40

示例 2

讓我們看看以下示例,我們將建立一個 unordered_multimap 物件和一個分配器型別物件,並將分配器與 Pair<char, int> 進行比較。

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

輸出

以下是以上程式碼的輸出:

Is allocator Pair<char, int> : true

示例 3

考慮另一種情況,我們將使用 get_allocator() 函式。

#include <unordered_map>
#include <iostream>
using namespace std;
typedef unordered_multimap<char, int> Mymap;
typedef allocator<pair<const char, int> > Myalloc;
int main() {
   Mymap obj;
   Mymap::allocator_type al = obj.get_allocator();
   cout << "al == std::allocator() is "<< std::boolalpha << (al == Myalloc()) << std::endl;
   return (0);
}

輸出

以上程式碼的輸出如下:

al == std::allocator() is true
廣告