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

set::get_allocator() ใน C++ STL


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

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

Set ใน C++ STL เป็นคอนเทนเนอร์ที่เก็บ องค์ประกอบที่ไม่ซ้ำกัน (unique) ในลำดับที่จัดเรียงแล้ว ค่าขององค์ประกอบระบุตัวตนของมันเอง เมื่อเพิ่มค่าใน set แล้วไม่สามารถแก้ไขได้ แต่ยังสามารถลบหรือเพิ่มค่าใหม่ได้ Set ถูกนำไปใช้งานเป็น binary search tree

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

get_allocator() เป็นฟังก์ชันในตัวของ C++ STL ที่ประกาศใน header file <set> ฟังก์ชันนี้ส่งคืน สำเนาของ allocator object ของ set container ที่เกี่ยวข้อง ใช้สำหรับจัดสรรหน่วยความจำ (memory chunks) ให้กับ set container

Allocator คือออบเจ็กต์ที่รับผิดชอบการจัดสรรหน่วยความจำแบบไดนามิกของ set container

ไวยากรณ์ (Syntax)

Set1.get_allocator();

พารามิเตอร์ (Parameters)

ฟังก์ชันนี้ไม่รับพารามิเตอร์ใดๆ

ค่าที่ส่งคืน (Return Value)

ส่งคืน allocator หรือสำเนาของ allocator ที่เกี่ยวข้องกับฟังก์ชัน

ตัวอย่างโค้ดเต็ม

#include <iostream>
#include <set>
using namespace std;

void input(int* arr) {
    for(int i = 0; i <= 5; i++)
        arr[i] = i;
}

void output(int* arr) {
    for (int i = 0; i <= 5; i++)
        cout << arr[i] << " ";
    cout << endl;
}

int main() {
    set<int> mySet;
    int* arr;
    
    // จัดสรรหน่วยความจำ 6 int ผ่าน allocator ของ set
    arr = mySet.get_allocator().allocate(6);
    input(arr);
    output(arr);
    
    // คืนหน่วยความจำ
    mySet.get_allocator().deallocate(arr, 6);
    return 0;
}

ผลลัพธ์ (Output)

0 1 2 3 4 5