C ++ set get_allocator()函數(shù)用于返回分配器對(duì)象的副本,該對(duì)象有助于構(gòu)造set容器。
allocator_type get_allocator() const; //C++ 11 之前 allocator_type get_allocator() const noexcept; //C++ 11 之后
沒(méi)有
返回與集合容器關(guān)聯(lián)的分配器。
不變。
沒(méi)有變化。
容器被訪問(wèn)。
同時(shí)訪問(wèn)set的元素是安全的。
此函數(shù)從不拋出異常。
讓我們看一個(gè)簡(jiǎn)單的實(shí)例:
#include <iostream>
#include <set>
using namespace std;
int main(void) {
set<double> m;
double *p;
p = m.get_allocator().allocate(3);
//double 為 8
cout << "分配的大小 = " << sizeof(*p) * 4 << endl;
return 0;
}輸出:
分配的大小 = 32
讓我們看一個(gè)簡(jiǎn)單的實(shí)例:
#include <iostream>
#include <set>
using namespace std;
int main ()
{
set<int> myset;
int * p;
unsigned int i;
// 使用myset的分配器分配一個(gè)包含5個(gè)元素的數(shù)組:
p=myset.get_allocator().allocate(5);
// 給數(shù)組賦一些值
for (i=0; i<5; i++) p[i]=(i+1)*10;
cout << "已分配的數(shù)組包含:";
for (i=0; i<5; i++) cout << ' ' << p[i];
cout << '\n';
myset.get_allocator().deallocate(p,5);
return 0;
}輸出:
已分配的數(shù)組包含: 10 20 30 40 50
讓我們看一個(gè)簡(jiǎn)單的示例,檢查分配器是否可互換:
#include <set>
#include <iostream>
using namespace std;
int main()
{
set<int>::allocator_type s1_Alloc;
set<int>::allocator_type s2_Alloc;
set<double>::allocator_type s3_Alloc;
set<int>::allocator_type s4_Alloc;
//以下行聲明對(duì)象
//使用默認(rèn)分配器。
set<int> s1;
set<int>::allocator_type s2;
set<double>::allocator_type s3;
s1_Alloc = s1.get_allocator();
cout << "可以分配的整數(shù)數(shù)量"
<< endl << "在空閑內(nèi)存耗盡之前: "
<< s2.max_size() << "." << endl;
cout << "\n可以分配的雙浮點(diǎn)數(shù)"
<< endl << "在空閑內(nèi)存耗盡之前: "
<< s3.max_size() << "." << endl;
//以下行創(chuàng)建一個(gè)集合s4
//使用多重集合s1的分配器。
set <int> s4(less<int>(), s1_Alloc);
s4_Alloc = s4.get_allocator();
//如果兩個(gè)分配器可以互換
//每個(gè)分配的存儲(chǔ)空間可以是
//被另一個(gè)釋放
if (s1_Alloc == s4_Alloc)
{
cout << "\n這些分配器是可互換的。"<< endl;
}
else
{
cout << "\n這些分配器是不可互換的。"<< endl;
}
return 0;
}輸出:
可以分配的整數(shù)數(shù)量 在空閑內(nèi)存耗盡之前: 1073741823. 可以分配的雙浮點(diǎn)數(shù) 在空閑內(nèi)存耗盡之前: 536870911. 這些分配器是可互換的。
讓我們看一個(gè)簡(jiǎn)單的實(shí)例:
#include <iostream>
#include <set>
using namespace std;
int main ()
{
set < int > c ;
int * p ;
p = c . get_allocator () . allocate ( 2 );
p [ 0 ] = 42 ;
p [ 1 ] = 43 ;
cout << p [ 0 ] << ", " << p [ 1 ] << endl ;
c . get_allocator () . deallocate ( p , 2 );
}輸出:
42, 43