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;

参数

此函数不接受任何参数。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

返回值

此函数返回与 unordered_multimap 关联的分配器。

示例 1

在以下示例中,让我们看看 unordered_multimap::get_allocator() 函数的使用方法。

Open Compiler
#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> 进行比较。

Open Compiler
#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() 函数。

Open Compiler
#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
广告