C++;优先级队列概念和基础使用

优先级队列;
1. 队列是一种容器适配器,专门用于在FIFO上下文(先进先出)中操作,其中从容器一端插入元素,另一端
提取元素。
2. 队列作为容器适配器实现,容器适配器即将特定容器类封装作为其底层容器类,queue提供一组特定的
成员函数来访问其元素。元素从队尾入队列,从队头出队列。
3. 底层容器可以是标准容器类模板之一,也可以是其他专门设计的容器类。该底层容器应至少支持以下操
作:

empty:检测队列是否为空
size:返回队列中有效元素的个数
front:返回队头元素的引用
back:返回队尾元素的引用
push_back:在队列尾部入队列
pop_front:在队列头部出

//优先级队列;;;
#include<functional>
int main()
{
	priority_queue<int>q1;//优先级堆列
	q1.push(4);
	q1.push(3);
	q1.push(6);
	q1.push(7);
	cout << q1.size() <<endl;
	cout << q1.top() << endl;

	q1.pop();
	cout << q1.size() << endl;
	cout << q1.top() << endl;

	vector<int>v{3,1,2,0,9,8,6,7,2};

	//创建大堆
	priority_queue<int>q2(v.begin(), v.end());//默认创建大堆
	priority_queue<int,vector<int>, greater<int>>q3(v.begin(),v.end());//创建小堆
	system("pause");
	return 0;
}
class Date
{
public:
	Date(int year,int month,int day):
		_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;
};
int main()
{
	Date d1(2019, 6, 27);
	Date d2(2019, 6, 28);
	Date d3(2019, 6, 25);

	创建大堆;
	//priority_queue<Date*,vector<Date*>,greater<Date*>> q;
	//q.push(&d1);
	//q.push(&d2);
	//q.push(&d3);

    //创建小堆;需要提供<<重载;
    priority_queue<Date, vector<Date>, greater<Date>> q2;
	q2.push(Date(2019, 6, 27));
	q2.push(Date(1997, 2, 25));
	q2.push(Date(2019, 6, 28));

	cout << q2.top() << endl;

	system("pause");
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

童无极

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值