C++ STL中使用push在priority_queue末尾插入

C++ STL中使用push在priority_queue末尾插入

要在 priority_queue 中插入元素,可使用成员方法 push( ):
numsInPrioQ.push (5); // elements are organized in sorted order
要在 priority_queue 开头删除元素,可使用 pop( ):
numsInPrioQ.pop (); // removes element at front
程序清单 24.6 演示了如何使用 priority_queue 的成员函数。

0: #include <queue>
1: #include <iostream>
2:
3: int main ()
4: {
5: using namespace std;
6:
7: priority_queue <int> numsInPrioQ;
8: cout << "Inserting {10, 5, -1, 20} into the priority_queue" << endl;
9: numsInPrioQ.push (10);
10: numsInPrioQ.push (5);
11: numsInPrioQ.push (-1);
12: numsInPrioQ.push (20);
13:
14: cout << "Deleting the " << numsInPrioQ.size () << " elements" << endl;
15: while (!numsInPrioQ.empty ())
16: {
17: cout << "Deleting topmost element: " << numsInPrioQ.top () << endl;
18: numsInPrioQ.pop ();
19: }
20:
21: return 0;
22: }

输出:
Inserting {10, 5, -1, 20} into the priority_queue
Deleting the 4 elements
Deleting topmost element: 20
Deleting topmost element: 10
Deleting topmost element: 5
Deleting topmost element: -1

分析:
这个示例首先将一些整数插入到 priority_queue 中(如第 9~12 行所示),然后使用 pop( )删除队首
元素,如第 18 行所示。从输出可知,值最大的元素位于队首,因此调用 priority_queue::pop( )将删除容
器中值最大的元素;可通过方法 top( )访问该元素,如第 17 行所示。由于这里没有提供优先级谓词,
优先级队列自动将元素按降序排列(最大的值位于队首)。
下一个示例(程序清单 24.7)使用谓词 std::greater 实例化一个 priority_queue。该谓词导致优
先级队列认为包含的数字最小的元素为最大的元素,并将其放在队首。

0: #include <queue>
1: #include <iostream>
2: #include <functional>
3: int main ()
4: {
5: using namespace std;
6:
7: // Define a priority_queue object with greater <int> as predicate
8: priority_queue <int, vector <int>, greater <int>> numsInPrioQ;
9:
10: cout << "Inserting {10, 5, -1, 20} into the priority queue" << endl;
11: numsInPrioQ.push (10);
12: numsInPrioQ.push (5);
13: numsInPrioQ.push (-1);
14: numsInPrioQ.push (20);
15:
16: cout << "Deleting " << numsInPrioQ.size () << " elements" << endl;
17: while (!numsInPrioQ.empty ())
18: {
19: cout << "Deleting topmost element " << numsInPrioQ.top () << endl;
20: numsInPrioQ.pop ();
21: }
22:
23: return 0;
24: }

对C++编程技术感兴趣的朋友请点击这里:零声学院C/C++服务器课程

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值