อย่างที่เราทราบกันดีอยู่แล้วว่าโครงสร้างข้อมูลคิวเป็นโครงสร้างข้อมูลแบบเข้าก่อนออกก่อน คิวมีรูปแบบบางอย่างด้วย นี่คือ Dequeue และ Priority Queue
ที่นี่เราจะเห็นรูปแบบหนึ่งของคิว นั่นคือคิวลำดับความสำคัญ ในโครงสร้างนี้ แต่ละองค์ประกอบในคิวมีลำดับความสำคัญของตัวเอง เมื่อเราแทรกรายการลงในคิว เราต้องกำหนดค่าลำดับความสำคัญด้วย มันจะลบองค์ประกอบที่มีลำดับความสำคัญสูงสุดในตอนแรก วิธีหนึ่งที่ง่ายที่สุดในการใช้คิวลำดับความสำคัญคือการใช้โครงสร้างข้อมูลฮีป
ให้เราดูรหัส C ++ หนึ่งรหัสสำหรับคิวลำดับความสำคัญ STL ที่นี่ลำดับความสำคัญถูกกำหนดตามค่า ดังนั้นค่าที่สูงกว่าจะถือเป็นองค์ประกอบที่มีลำดับความสำคัญสูงสุด
อัลกอริทึม
insert(key, priority): Begin insert key at the end of the heap heapify the array based on the priority End delete(): Begin item := root element root := last element from array heapify the array to arrange based on priority return item End
ตัวอย่าง
#include <iostream>
#include <queue>
using namespace std;
void dequeElements(priority_queue <int> que) {
priority_queue <int> q = que;
while(!q.empty()){
cout << q.top() << " ";
q.pop();
}
cout << endl;
}
int main() {
priority_queue <int> que;
que.push(10);
que.push(20);
que.push(30);
que.push(5);
que.push(1);
cout << "Currently que is holding : ";
dequeElements(que);
cout << "Size of queue : " << que.size() << endl;
cout << "Element at top position : " << que.top() << endl;
cout << "Delete from queue : ";
que.pop();
dequeElements(que);
cout << "Delete from queue : ";
que.pop();
dequeElements(que);
} ผลลัพธ์
Currently que is holding : 30 20 10 5 1 Size of queue : 5 Element at top position : 30 Delete from queue : 20 10 5 1 Delete from queue : 10 5 1