开发app的网站有哪些,微信小程序麻将辅助免费,拥有域名后怎么搭建网站,企业文化案例priority_queuepriority_queue 优先队列#xff0c;其底层是用堆来实现的。在优先队列中#xff0c;队首元素一定是当前队列中优先级最高的那一个。在优先队列中#xff0c;没有 front() 函数与 back() 函数#xff0c;而只能通过 top() 函数来访问队首元素#xff08;也可…priority_queuepriority_queue 优先队列其底层是用堆来实现的。在优先队列中队首元素一定是当前队列中优先级最高的那一个。在优先队列中没有 front() 函数与 back() 函数而只能通过 top() 函数来访问队首元素也可称为堆顶元素也就是优先级最高的元素。
一、基本数据类型的优先级设置
此处指的基本数据类型就是 int 型double 型char 型等可以直接使用的数据类型优先队列对他们的优先级设置一般是数字大的优先级高因此队首元素就是优先队列内元素最大的那个如果是 char 型则是字典序最大的。
//下面两种优先队列的定义是等价的priority_queueint q;priority_queueint,vectorint,lessint ;//后面有一个空格其中第二个参数( vector )是来承载底层数据结构堆的容器第三个参数( less )则是一个比较类less 表示数字大的优先级高而 greater 表示数字小的优先级高。
如果想让优先队列总是把最小的元素放在队首只需进行如下的定义
priority_queueint,vectorint,greaterint q;
示例代码
void test1(){//默认情况下数值大的在队首位置(降序)priority_queueint q;for(int i 0;i 10;i )q.push(i);while(!q.empty()){coutq.top() ;q.pop();}coutendl;//greaterint表示数值小的优先级越大priority_queueint,vectorint,greaterint Q;for(int i 0;i 10;i )Q.push(i);while(!Q.empty()){coutQ.top() ;Q.pop();}}
二、结构体的优先级设置
1.方式一重载运算符 ‘’可以在结构体内部重载 ‘’改变小于号的功能(例如把他重载为大于号)
struct student{int grade;string name;//重载运算符grade 值高的优先级大friend operator (student s1,student s2){return s1.grade s2.grade;}};
示例代码
void test2(){priority_queuestudent q;student s1,s2,s3;s1.grade 90;s1.name Tom;s2.grade 80;s2.name Jerry;s3.grade 100;s3.name Kevin;q.push(s1);q.push(s2);q.push(s3);while(!q.empty()){coutq.top().name:q.top().gradeendl;q.pop();} }/*结果Kevin:100Tom:90Jerry:80*/
2.方式二把重载的函数写在结构体外面将比较函数写在结构体外面作为参数传给优先队列。
struct fruit{string name;int price;};struct cmp{// 表示 price 大的优先级高bool operator() (fruit f1,fruit f2){return f1.price f2.price;}};
示例代码
void test3(){priority_queuefruit,vectorfruit,cmp q;fruit f1,f2,f3;f1.name apple;f1.price 5;f2.name banana;f2.price 6;f3.name pear;f3.price 7;q.push(f1);q.push(f2);q.push(f3);while(!q.empty()){coutq.top().name:q.top().priceendl;q.pop();}}/*结果pear:7banana:6apple:5*/原博客链接https://blog.csdn.net/pzhu_cg_csdn/article/details/79166858