priority_queue(优先队列)是一种特殊的队列数据结构,它的每个元素都有一个与之关联的优先级。在优先队列中,元素按照优先级的顺序进行排列,具有较高优先级的元素排在前面,较低优先级的元素排在后面。
C++标准库中的priority_queue:
下面是riority_queue的简单模拟实现:
#pragma once #include <vector> #include <iostream> using namespace std; namespace hsl { template<class T, class Container = vector<T>,class Compar = Less<T>> class priority_queue { public: priority_queue() {} template <class InputIterator> priority_queue(InputIterator first, InputIterator last) :_con(first, last) { for (int i = (_con.size() - 2) / 2; i >= 0; i--) { adjust_down(); } } void adjust_up(int child) { Compar com; int parent = (child - 1) / 2; while (child > 0) { //if (_con[parent] < _con[child]) if(com(_con[parent],_con[child])) { swap(_con[parent], _con[child]); child = parent; parent = (child - 1) / 2; } else { break; } } } void adjust_down(size_t parent) { Compar com; size_t child = parent * 2 + 1; while (child < _con.size()) { if (child + 1 < _con.size() && com(_con[child] , _con[child + 1])) { ++child; } if (com(_con[parent] , _con[child])) { swap(_con[parent], _con[child]); parent = child; child = parent * 2 + 1; } else { break; } } } void push(const T& x) { _con.push_back(x); adjust_up(_con.size()-1); } void pop() { swap(_con[0], _con[_con.size() - 1]); _con.pop_back(); adjust_down(0); } const T& top() { return _con[0]; } bool empty() { return _con.empty(); } size_t size() { return _con.size(); } private: Container _con; }; template<class T> class Less { public: const T& operator()(const T& a, const T& b) { return a < b; } }; template<class T> class Greater { public: const T& operator()(const T& a, const T& b) { return a > b; } }; }