【C++】C++ STL探索:Priority Queue与仿函数的深入解析(二)https://developer.aliyun.com/article/1617383
四、priority_queue.h
#pragma once #include <vector> #include <algorithm> namespace bit { class Date { public: friend ostream& operator<<(ostream& _cout, const Date& d); Date(int year = 1900, int month = 1, int day = 1) : _year(year) , _month(month) , _day(day) {} bool operator<(const Date& d)const { return (_year < d._year) || (_year == d._year && _month < d._month) || (_year == d._year && _month == d._month && _day < d._day); } bool operator>(const Date& d)const { return (_year > d._year) || (_year == d._year && _month > d._month) || (_year == d._year && _month == d._month && _day > d._day); } private: int _year; int _month; int _day; }; ostream& operator<<(ostream& _cout, const Date& d) { _cout << d._year << "-" << d._month << "-" << d._day; return _cout; } template<class T> class Less { public: bool operator()(const T& x, const T& y) { return x < y; } }; template<class T> class Greater { public: bool operator()(const T& x, const T& y) { return x > y; } }; template<class T, class Containor = vector<T>, class Compare = Less<T>> class priority_queue { public: Compare _com; void push(const T& x) { _con.push_back(x); adjust_up(_con.size() - 1); } void adjust_up(size_t child) { size_t parent = (child - 1) / 2; while (child > 0) { //if (_con[parent] < _con[child]) if (_com(_con[parent], _con[child])) { std::swap(_con[child], _con[parent]); child = parent; parent = (child - 1) / 2; } else break; } } void pop() { std::swap(_con[0], _con[_con.size() - 1]); _con.pop_back(); adjust_down(0); } void adjust_down(size_t parent) { size_t child = parent * 2 + 1; while (child < _con.size()) { if (child + 1 < _con.size() && _con[child] < _con[child + 1]) child++; //if (_con[parent] < _con[child]) if (_com(_con[parent], _con[child])) { std::swap(_con[child], _con[parent]); parent = child; child = parent * 2 + 1; } else break; } } const T& top() { return _con[0]; } size_t size() { return _con.size(); } bool empty() { return _con.empty(); } private: Containor _con; }; void test1() { priority_queue<int> pq; pq.push(3); pq.push(2); pq.push(2); pq.push(110); while (!pq.empty()) { cout << pq.top() << " "; pq.pop(); } cout << endl; } class GteaterDate { public: bool operator()(const Date* p1, const Date* p2) { return *p1 > *p2; } }; void test2() { priority_queue <Date*, vector<Date*>, GteaterDate> pqptr; //priority_queue <Date*, vector<Date*>> pqptr; pqptr.push(new Date(2024, 4, 14)); pqptr.push(new Date(2024, 4, 11)); pqptr.push(new Date(2024, 4, 15)); while (!pqptr.empty()) { cout << *(pqptr.top()) << " "; pqptr.pop(); } cout << endl; } }
以上就是本篇文章的所有内容,在此感谢大家的观看!这里是店小二呀C++笔记,希望对你在学习C++语言旅途中有所帮助!