1.函数运算符重载
#include <functional>
void Testpriority_queue()
{
priority_queue<int, vector<int>, greater<int>> q;
q.push(4);
q.push(5);
q.push(1);
q.push(2);
q.push(9);
q.push(8);
q.push(7);
cout << q.size() << endl;
cout << q.top() << endl;
}
class Date
{
public:
Date(int year, int month, int day)
: _year(year)
, _month(month)
, _day(day)
{}
自定义类型的Date默认不能进行比较,必须给出方法
第一种:运算符重载
bool operator<(const Date& d)const
{
return _day < d._day;
}
bool operator>(const Date& d)const
{
return _day > d._day;
}
private:
size_t _year;
size_t _month;
size_t _day;
};
void Test1()
{
Date d1(2020, 5, 6);
Date d2(2020, 5, 7);
Date d3(2020, 5, 8);
priority_queue<Date, vector<Date>, greater<Date>> p;
p.push(d1);
p.push(d2);
p.push(d3);
}
2.函数指针
class Date
{
public:
Date(int year, int month, int day)
: _year(year)
, _month(month)
, _day(day)
{}
friend bool IsLess(const Date& left, const Date& right);
private:
size_t _year;
size_t _month;
size_t _day;
};
bool IsLess(const Date& left, const Date& right)
{
return left._day < right._day;
}
typedef bool(*Less)(const Date& left, const Date& right);
void Test2()
{
Date d1(2020, 5, 6);
Date d2(2020, 5, 7);
Date d3(2020, 5, 8);
priority_queue<Date, vector<Date>, Less> p(IsLess);
p.push(d1);
p.push(d2);
p.push(d3);
}
3.仿函数(函数对象)
class Date
{
public:
Date(int year, int month, int day)
: _year(year)
, _month(month)
, _day(day)
{}
int Getday()
{
return _day;
}
private:
int _year;
int _month;
int _day;
};
class Greater
{
public:
bool operator()(Date& left, Date& right)
{
return left.Getday() > right.Getday();
}
};
void Test3()
{
Date d1(2020, 5, 6);
Date d2(2020, 5, 7);
Date d3(2020, 5, 8);
priority_queue<Date, vector<Date>, Greater> p;
p.push(d1);
p.push(d2);
p.push(d3);
}
4.主函数
int main()
{
Test3();
return 0;
}