首页 > 编程知识 正文

队列queue的用法,reach的用法

时间:2023-05-05 14:46:11 阅读:30219 作者:4976

既然是队列,就必须首先包含头文件#include queue。 他与queue的不同之处在于,可以自定义数据优先级,使高优先级的数据排在队列之前,并优先离开队列

首选队列具有队列的所有特性,包括基本操作,但只是在此基础上添加了内部排序,本质上是堆实现

与队列基本操作相同的:

top访问队列标头元素empty队列是否为空size返回队列中的元素数。 在队列末尾插入推式元素。 emplace立即构建元素并将其插入队列。 pop是队列标头元素swap的交换内容定义: priority_queueType,Container,Functional

类型为数据类型,容器为容器类型。 (容器必须是以vector、deque等数组实现的容器,但不能使用列表。 默认情况下,STL使用vector ),Functional是比较方法,需要使用自定义数据类型时必须传递这三个参数。 使用基本数据类型时,只需传递数据类型,默认值为大山

一般来说:

//升序队列priority_queue int、vectorint、greaterint q; //降序队列priority_queue int、vectorint、lessint q; //greater和less是std实现的两个伪函数()一个类的使用看起来像一个函数。 其实现是在类中实现operator (),其行为类似于函数。 是伪函数类。 (include iostream # includequeueusingnamespacestd; 对于int main ()//基本类型,默认情况下为顶级堆priority_queueint a; 等同于priority_queueint、vectorint、lessint a; priority_queueint、vectorint、greaterint c; //这就是小山顶上的priority_queuestring b; for(intI=0; i 5; I ) a.push(I ); c.push(I; } while (! a.empty () ) { cout a.top () ) ) ) ) ) ) ) ); a.pop (; } cout endl; while (! c.empty () ) { cout c.top () ) ) ) ) ) ) ) ); c.pop (; } cout endl; b .推送(ABC ); b .推送(ABCD ); b .推送(CBD ); while (! b.empty () ) ({ cout b.top ) ) ) ) ) ) ) ) ); b.pop (; } cout endl; 返回0; }输出

4 3 2 1 00 1 2 3 4cbd abcd abc 2.pari比较首先比较第一个元素,比较第一个元素相等第二个元素

# include iostream # include queue # includevectorusingnamespacestd; int main () { priority_queuepairint,int a; pairint,intb (1,2 ); pairint,intc (1,3 ); pairint,intd (2,5 ); a.push(d; a.push(c; a.push(b; while (! a.empty () ({ cout a.top ).first ' ' a.top ) ).second 'n '; a.pop (; }输出

2 51 31 2 3 .对于自定义类型

# include iostream # includequeueusingnamespacestd; //方法1结构tmp1//运算符重载{ int x; tmp1(inta ) x=a; } bool operator (常数tmp 1a )常数) returnxa.x; //大屋顶山}; //方法2结构tmp2//伪函数{ bool operator () tmp1 a,tmp1 b ) { return a.x b.x; //大屋顶山}; int main () tmp1a ) ); TMP1b(2; TMP1c(3; priority_queuetmp1 d; d.push(b; d.push(c; d.push(a; while (! d.empty () ) { cout d.top ) ).x 'n '; d.pop (; } cout endl; priority_queuetmp1、vectortmp1、tmp2 f; f.push(c; f.push(b; f.push(a; while (! f.empty () ) { cout f.top ) ).x 'n '; f.pop (; }输出

321321

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。