**prioroty_queue我們可以認爲就是一個堆,我們堆的性質和std裏面的這個容器其實定義性質都是差不多的。
在默認情況了,qriority_queue堆頂元素是最大的,也就是大堆,但是我們往往知道如果是內置類型我們想換成小堆只需要加上priority<int, vector,greater>就可以了這樣也是比較簡單的,雖然加上這麼一個堆轉換語句看起來一下子邊長了,好像變麻煩了,但是這個語句也是想當好記的,至少給priority這個單詞好記。
好了,進入正題吧,我們是要重載自定義類型,那麼自定義類型的堆數據應該如何重載呢?
比如我們想重載一個日期類:例如d1(2019,1,7) d2(2019,1,8) d3(2019,1,9) d4(2019,1,10) d5(2019,1,11)顯然堆頂元素應該是d5的,但是這個比較就比較不一樣了,我們需要對年月日經行比較。這個樣我們必需對自定義類型類當中經行運算符重載提供兩個這樣的比較函數== "operator < "== "operator > "
- 好了類看一下基本的設置吧
#include <vector>
#include <queue>
#include <functional> // greater算法的頭文件
class Date {
public:
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);
}
friend ostream& operator<<(ostream& _cout, const Date& d)
{
_cout << d._year << "-" << d._month << "-" << d._day;
return _cout; }
private:
int _year;
int _month;
int _day;
};
void TestPriorityQueue() {
// 大堆,需要用戶在自定義類型中提供<的重載
priority_queue<Date> q1;
q1.push(Date(2018, 10, 29));
q1.push(Date(2018, 10, 28));
q1.push(Date(2018, 10, 30));
cout << q1.top() << endl;
// 如果要創建小堆,需要用戶提供>的重載
priority_queue<Date, vector<Date>, greater<Date>> q2;
q2.push(Date(2018, 10, 29));
q2.push(Date(2018, 10, 28));
q2.push(Date(2018, 10, 30));
cout << q2.top() << endl;
}
int main()
{
TestPriorityQueue();
return 0;
}
好了,自定義類型堆創建成功。