Priority Queue
#include <queue>
priority_queue<int> pq; // create priority queue for ints
pq.push(10); // push integer in priority queue
pq.top(); // get the top element from pq without popping it
pq.pop(); // pop the top element from pq. It returns void
while(!pq.empty()){ // pq.empty returns whether pq is empty or not
}// priority queue with custom object
class Student {
private:
string name;
int marks;
public:
Student(string name, int marks){
this->name = name;
this->marks = marks;
}
string getName(){
return name;
}
int getMarks() {
return marks;
}
};
class StudentComparator {
public:
bool operator() (Student& lowerPriorityStudent, Student& higherPriorityStudent)
{
return higherPriorityStudent.getMarks() > lowerPriorityStudent.getMarks();
}
};
int main() {
priority_queue<Student, vector<Student>, StudentComparator> pq;
pq.push(Student("A1", 90));
pq.push(Student("A2", 12));
pq.push(Student("A3", 45));
pq.push(Student("A4", 30));
pq.push(Student("A5", 50));
while(!pq.empty()){
Student top = pq.top();
cout << top.getName() << ", " << top.getMarks() << endl;
pq.pop();
}
return 0;
}
Result:
A1, 90
A5, 50
A3, 45
A4, 30
A2, 12
Last updated