Bài ví dụ về sử dụng hàng đợi ưu tiên
C++ hấp dẫn hơn C# nhiều. Nó có những thư viện cài đặt sẵn các giải thuật và quá khó hiểu để sử dụng.
Mình thử sửa lại ví dụ trên cplusplus sử dụng cấu trúc tự tạo elem với class dùng để so sánh. Tổng kết:
1 hàng đợi ưu tiên cần:
Bạn có thể tham khảo thêm tại: http://www.cplusplus.com/reference/stl/priority_queue/priority_queue/
Còn đây là bài mình đã chỉnh sửa:
Mình thử sửa lại ví dụ trên cplusplus sử dụng cấu trúc tự tạo elem với class dùng để so sánh. Tổng kết:
1 hàng đợi ưu tiên cần:
- 1 cấu trúc lưu trữ.
- 1 phép toán so sánh
- Các hàm hỗ trợ: top(), size(), pop(), push(), empty().
Bạn có thể tham khảo thêm tại: http://www.cplusplus.com/reference/stl/priority_queue/priority_queue/
Còn đây là bài mình đã chỉnh sửa:
// constructing priority queues #include <iostream> #include <queue> using namespace std; //typedef int elem; struct elem{ int dinh; int trongso; }; class mycomparison { bool reverse; public: mycomparison(const bool& revparam=false) {reverse=revparam;} bool operator() (const elem& lhs, const elem&rhs) const { if (reverse) return (lhs.trongso>rhs.trongso); else return (lhs.trongso<rhs.trongso); } }; int main () { elem a,b; elem tg; a.dinh=1; a.trongso=2; b.dinh=3; b.trongso=5; // using mycomparison: priority_queue< elem, vector<elem>, mycomparison > fourth; fourth.push(b); fourth.push(a); while(!fourth.empty()) { tg=fourth.top(); cout<<tg.dinh<<" "; fourth.pop(); } return 0; }
Nhận xét
Đăng nhận xét