priority_queue:优先级队列(详解+代码示例)

优先级队列本质:堆

堆:完全二叉树+条件:任意节点都要比孩子节点小(大)--->小堆(大堆)

  1. 包含<queue>头文件+std

  1. 底层就是堆

  1. 模板参数列表的说明:

template<class T,class Container<T>,class Compare = less<typename Container::value_type>>

①T是优先级队列中存储的元素类型

②优先级队列的元素默认是存储到vector中。

③优先级队列中元素的比较方式-----默认按照小于的方式比较

注意:虽然按照小于的方式比较,但是默认创建的是大堆。

// priority_queue默认是按照小于的方式比较,创建出来的是大堆
void TestPriorityQueue1()
{
    priority_queue<int> q;
    q.push(5);
    q.push(9);
    q.push(8);
    q.push(1);
    q.push(2);
    q.push(3);
    q.push(7);
    q.push(4);
    q.push(0);
    q.push(6);

    cout << q.size() << endl;
    cout << q.top() << endl;

    q.pop();
    q.pop();
    q.pop();
    cout << q.size() << endl;
    cout << q.top() << endl;
}

创建小堆,必须将堆中的元素按照大于的方式比较

void TestPriorityQueue2()
{
    // priority_queue<int, greater<int>> q;这样不行,需要把vector传进去

    priority_queue<int, vector<int>, greater<int>> q;
    q.push(5);
    q.push(9);
    q.push(2);
    q.push(1);
    q.push(8);
    q.push(3);
    q.push(7);
    q.push(4);
    q.push(0);
    q.push(6);

    cout << q.size() << endl;
    cout << q.top() << endl;

    q.pop();
    q.pop();
    q.pop();
    cout << q.size() << endl;
    cout << q.top() << endl;
}

priority_queue 是容器适配器,它提供常数时间的(默认)最大元素查找,对数代价的插入与释出。

可用用户提供的 Compare 更改顺序,例如,用 std::greater<T> 将导致最小元素作为 top() 出现。

用 priority_queue 工作类似管理某些随机访问容器中的堆,优势是不可能突然把堆非法化。

区间构造

    int array[] = { 5,6,8,2,3,4,7,1,9,0 };
    priority_queue<int> q(array, array + sizeof(array) / sizeof(array[0]));
    priority_queue<int> q(v.begin(), v.end());//两种方式

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值