Priority Queue একটি কন্টেইনার অ্যাডাপ্টার যেখানে সবচেয়ে বড় উপাদানটি সবসময় শীর্ষে (top) থাকে। উপাদানগুলো অ-নিম্নক্রমে (non-decreasing order) সাজা থাকে। উচ্চ প্রায়োরিটির উপাদান নিম্ন প্রায়োরিটির উপাদানের আগে সার্ভ করা হয়। ডিফল্টভাবে less<T> কমপ্যারেটর ব্যবহার করে मैক্স-হিপ (max-heap) আচরণ করে।
প্রধান ফাংশন ও বর্ণনা:
- pq.size() – প্রায়োরিটি কিউয়ের আকার রিটার্ন করে।
- pq.push() – প্রায়োরিটি কিউয়ে উপাদান যোগ করে।
- pq.pop() – শীর্ষ উপাদানটি মুছে ফেলে।
- pq.top() – শীর্ষ উপাদান (সর্বোচ্চ মান) রিটার্ন করে।
উদাহরণ কোড: ইন্টারেক্টিভ প্রায়োরিটি কিউ প্রোগ্রাম
#include <iostream>
#include <queue>
#include <string>
#include <cstdlib>
using namespace std;
int main() {
priority_queue<int> pq; // ডিফল্ট: max-heap
int choice, value;
while (true) {
cout << "1. Size of the Priority Queue" << endl;
cout << "2. Insert Element into the Priority Queue" << endl;
cout << "3. Delete Element from the Priority Queue" << endl;
cout << "4. Top Element of the Priority Queue" << endl;
cout << "5. Exit" << endl;
cout << "Enter your Choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Size of the Queue: " << pq.size() << endl;
break;
case 2:
cout << "Enter value to be inserted: ";
cin >> value;
pq.push(value);
break;
case 3:
if (!pq.empty()) {
value = pq.top();
pq.pop();
cout << value << " Deleted" << endl;
} else {
cout << "Priority Queue is Empty" << endl;
}
break;
case 4:
if (!pq.empty())
cout << "Top Element of the Queue: " << pq.top() << endl;
else
cout << "Priority Queue is Empty" << endl;
break;
case 5:
exit(0);
default:
cout << "Wrong Choice" << endl;
}
}
return 0;
}
নমুনা আউটপুট
1. Size of the Priority Queue 2. Insert Element into the Priority Queue 3. Delete Element from the Priority Queue 4. Top Element of the Priority Queue 5. Exit Enter your Choice: 1 Size of the Queue: 0 ... Enter your Choice: 2 Enter value to be inserted: 7 ... Enter your Choice: 4 Top Element of the Queue: 7 Enter your Choice: 5 Exit code: 1
টিপ: মিন-হিপ (min-heap) বানাতে চাইলে priority_queue<int, vector<int>, greater<int>> pq; লিখুন।