C++ 中"priority_queue" 优先级队列实例详解

2025-05-27 0 36

C++ 中"priority_queue" 优先级队列实例详解

1. 简介

标准库队列使用了先进先出(FIFO)的存储和检索策略. 进入队列的对象被放置在尾部, 下一个被取出的元素则取自队列的首部. 标准库提供了两种风格的队列: FIFO 队列(FIFO queue, 简称 queue), 以及优先级队列(priority queue).

priority_queue 允许用户为队列中存储的元素设置优先级. 这种队列不是直接将新元素放置在队列尾部, 而是放在比它优先级低的元素前面. 标准库默认使用元素类型的 "<" 操作符来确定它们之间的优先级关系. 如需改变大小关系, 需要使用std::greater<temple>函数, 在functional头文件中.

2. 代码

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31
#include <iostream> // std::cout

#include <queue> // std::priority_queue

#include <vector> // std::vector

#include <functional> // std::greater

int main ()

{

int myints[]= {10,60,50,20};

std::priority_queue<int> intPQueue1 (myints, myints+4);

std::priority_queue<int, std::vector<int>, std::greater<int> >

intPQueue2 (myints,myints+4);

std::cout << "less than: " << std::endl;

while( !intPQueue1.empty() ){

int pvalue = intPQueue1.top();

std::cout << pvalue << " ";

intPQueue1.pop();

}

std::cout << std::endl;

std::cout << "bigger than: " << std::endl;

while( !intPQueue2.empty() ){

int pvalue = intPQueue2.top();

std::cout << pvalue << " ";

intPQueue2.pop();

}

std::cout << std::endl;

return 0;

}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 C++ 中"priority_queue" 优先级队列实例详解 https://www.kuaiidc.com/73478.html

相关文章

发表评论
暂无评论