C++ unordered_map::get_allocator() 函数



C++ 的 std::unordered_map::get_allocator() 函数用于获取与无序映射关联的分配器的副本。分配器负责为存储在无序映射中的元素分配和释放内存。

此函数不会修改无序映射,也不会抛出任何异常。

语法

以下是 std::unordered_map::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.

返回值

此函数返回一个分配器对象。

示例 1

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

Open Compiler
#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。

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