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

STL Priority Queue สำหรับ Structure หรือ Class ใน C++

STL Priority Queue เป็นการนำ Max Heap มาใช้งาน

นี่คือโปรแกรม C++ ของ STL Priority Queue สำหรับ Structure

อัลกอริทึม

Begin
    Define structure student
    Initialize variables in student
    Define structure comparemarks
    Overload student variables in comparemarks
    Use priority queue with structure
    Insert elements using student structure
    While queue not empty: Print elements
End.

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

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

#define ROW 6
#define COL 3

struct student {
    int roll, marks;
    student(int roll, int marks) : roll(roll), marks(marks) {}
};

struct comparemarks {
    bool operator()(student const& s1, student const& s2) {
        return s1.marks < s2.marks; // max-heap by marks
    }
};

int main() {
    priority_queue<student, vector<student>, comparemarks> M;
    int a[ROW][COL] = {{15, 50}, {16, 60}, {18, 70}, {14, 80}, {12, 90}, {20, 100}};
    for (int i = 0; i < ROW; ++i)
        M.push(student(a[i][0], a[i][1]));
    cout << "priority queue for structure ::" << endl;
    while (!M.empty()) {
        student s = M.top(); M.pop();
        cout << s.roll << " " << s.marks << "\n";
    }
    return 0;
}

ผลลัพธ์

priority queue for structure ::
20 100
12 90
14 80
18 70
16 60
15 50