Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ฟังก์ชัน map::get_allocator() ใน C++ STL


ในบทความนี้ เราจะอธิบายการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน map::get_allocator() ใน C++ STL

Map ใน C++ STL คืออะไร?

Map เป็น Associative Container ที่เก็บข้อมูลเป็นคู่ Key-Value จัดเรียงตาม Key อัตโนมัติ Key ต้องไม่ซ้ำกัน

map::get_allocator() คืออะไร?

map::get_allocator() คืน Allocator Object ที่ Map ใช้จัดสรรหน่วยความจำ สำหรับผู้ใช้ทั่วไป ใช้ได้น้อย มักใช้ในการพัฒนา Allocator แบบกำหนดเอง

Syntax

map_name.get_allocator();

Parameters

ไม่มีพารามิเตอร์

Return Value

Allocator Object ของ Map (คืนเป็น Copy)

ตัวอย่าง 1: ตรวจสอบ Allocator Type

#include <bits/stdc++.h>
using namespace std;

int main() {
    map<int, int> TP;
    auto tp = TP.get_allocator();
    
    cout << "Checking Is allocator Pair<int, int> : " 
         << boolalpha << (tp == allocator<pair<int, int>>());
    return 0;
}

ผลลัพธ์

Checking Is allocator Pair<int, int> : true

ตัวอย่าง 2: จัดสรรหน่วยความจำด้วย Allocator

#include <bits/stdc++.h>
using namespace std;

int main() {
    map<char, int> TP;
    pair<const char, int>* TP_pair;
    
    // จัดสรรพื้นที่ 5 Elements
    TP_pair = TP.get_allocator().allocate(5);
    
    cout << "Size after allocating is: " << sizeof(*TP_pair) * 5 << endl;
    
    // ควร deallocate เมื่อใช้เสร็จ
    TP.get_allocator().deallocate(TP_pair, 5);
    
    return 0;
}

ผลลัพธ์

Size after allocating is: 40

สรุป

get_allocator() ใช้ในระดับ Advanced สำหรับจัดการหน่วยความจำแบบกำหนดเอง ผู้ใช้ทั่วไปไม่ต้องใช้โดยตรง