C++ STL 中的 multimap get_allocator() 函数

c++server side programmingprogramming

本文将讨论 C++ STL 中 multimap::get_allocator() 函数的工作原理、语法和示例。

C++ STL 中的 Multimap 是什么?

Multimap 是一种关联容器,类似于 Map 容器。它能够以特定顺序存储由键值对和映射值组合而成的元素。在 Multimap 容器中,同一个键可以关联多个元素。数据在内部始终根据其关联键进行排序。

什么是 multimap::get_allocator()?

multimap::get_allocator() 函数是 C++ STL 中的一个内置函数,定义在 <map> 头文件中。get_allocator() 用于为 Multimap 容器分配内存块。此函数返回与其关联的容器的分配器对象的副本。

分配器是一个负责动态分配容器内存的对象。

语法

multi_name.get_allocator();

参数

此函数不接受任何参数。

返回值

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

输入 

int *Ptr;
std::multimap<int> newmap;
newmap.insert(make_pair(‘A’, 22));
newmap.insert(make_pair(‘B’, 78));
newmap.insert(make_pair(‘C’, 66));
newmap.insert(make_pair(‘D’, 81));
Ptr = mymap.get_allocator().allocate(4);

输出 

ptr = A:22 B:78 C:66 D:81

示例

#include <iostream>
#include <map>
using namespace std;
int main(){
   int arrsize;
   multimap<char, int> mul;
   pair<const char, int>* pr;
   pr = mul.get_allocator().allocate(15);
   // 为数组分配一些值
   arrsize = sizeof(multimap<char, int>::value_type) * 10;
   cout << "Size of the allocated array is: "<< arrsize << " bytes.\n";
   mul.get_allocator().deallocate(pr, 5);
   return 0;
}

输出

如果我们运行上述代码,它将生成以下输出 −

Size of the allocated array is: 80 bytes.

示例

#include <iostream>
#include <map>
using namespace std;
int main(){
   int arrsize;
   multimap<char, int> mul;
   pair<const char, int>* pr;
   pr = mul.get_allocator().allocate(2);
   // 为数组分配一些值
   arrsize = sizeof(multimap<char, int>::value_type) * 5;
   cout << "Size of the allocated array is: "<< arrsize << " bytes.\n";
   mul.get_allocator().deallocate(pr, 5);
   return 0;
}

输出

如果我们运行上述代码,它将生成以下输出 −

Size of the allocated array is: 40 bytes.

相关文章