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

Heap ใน C++ STL: make_heap, push_heap, pop_heap, sort_heap

ภาพรวม

บทความอธิบายฟังก์ชัน Heap ใน C++ STL () สำหรับจัดการ Max Heap

ฟังก์ชันหลัก

ฟังก์ชันหน้าที่
make_heap(first, last)แปลง range เป็น heap
push_heap(first, last)เพิ่ม element (ต้อง push_back ก่อน)
pop_heap(first, last)ลบ max element (ย้ายไป last, ต้อง pop_back)
sort_heap(first, last)เรียง heap ให้เป็น sorted ascending
is_heap(first, last)ตรวจสอบว่าเป็น heap หรือไม่
is_heap_until(first, last)คืน iterator จนถึงที่ยังเป็น heap

ตัวอย่างการใช้งาน

#include 
using namespace std;

int main() {
    vector heap = {33, 43, 53, 38, 28};
    make_heap(heap.begin(), heap.end());
    cout << "Top: " << heap.front() << endl;  // 53
    
    heap.push_back(60);
    push_heap(heap.begin(), heap.end());
    cout << "After insert: " << heap.front() << endl;  // 60
    
    pop_heap(heap.begin(), heap.end());
    heap.pop_back();
    cout << "After delete: " << heap.front() << endl;  // 53
    
    sort_heap(heap.begin(), heap.end());
    // heap ตอนนี้เรียง ascending: 28 33 38 43 53
    
    cout << is_heap(heap.begin(), heap.end());  // false (sorted ไม่ใช่ heap)
}

หมายเหตุสำคัญ

  • C++ heap เป็น Max Heap โดยค่าเริ่มต้น (มากที่สุดอยู่หน้า)
  • push_heap/pop_heap ต้องจัดการ vector size เอง (push_back/pop_back)
  • sort_heap ทำลาย heap property
  • Python heapq เป็น Min Heap ต้องใช้ค่าลบเพื่อทำ Max Heap

ผลลัพธ์ตัวอย่าง

Top element is : 53
Top element after insert : 60
Top element after deletion : 53
Before Sort : 53 43 33 38 28
After Sort : 28 33 38 43 53
The is not a heap
Heapify
The is a heap
The heap elements are : 53 43 33 38 28