priority_queue(优先级队列)

本文介绍了C++STL中的priority_queue容器适配器,包括其原理(堆数据结构)、主要成员函数如top()和emplace()的使用,以及声明时如何指定升序或降序队列。
摘要由CSDN通过智能技术生成

一、priority_queue介绍

  在C++中,priority_queue是一个容器适配器,它提供了常数时间的最大元素查找。它通常实现为堆。堆是一种数据结构,其中最大(或最小)元素始终位于顶部。priority_queue是一个模板类,定义在头文件中。它有三个模板参数:元素类型、容器类型和比较函数类型(可选)。默认情况下,它使用std::vector作为其底层容器 。

二、priority_queue使用

1.top()

top() 函数是 C++ STL 中 priority_queue 类的一个成员函数,用于返回优先队列中的第一个元素的引用 。在使用 top() 函数时,需要注意优先队列是否为空,否则会出现未定义的行为 。

int main()
{
	int a[] = { 3,6, 2,8,1 };
	priority_queue<int> q1;
	priority_queue<int> q2(a, a + 5);

	cout << "q1:" << q1.top() << endl;//报错
	cout << "q2:" << q2.top() << endl;//8

	return 0;
}

2.emplace()

构造和插入元素, 添加新元素。这个新元素是就地构造的,作为其构造函数的参数传递

int main()
{
    priority_queue<string> mypq;

    mypq.emplace("orange");
    mypq.emplace("strawberry");
    mypq.emplace("apple");
    mypq.emplace("pear");

    cout << "mypq contains:";
    while (!mypq.empty())
    {
        cout << ' ' << mypq.top();
        mypq.pop();
    }
    cout << '\n';

    return 0;
}

3.声明

//升序队列  小顶堆 great 小到大
priority_queue <int,vector<int>,greater<int> > pri_que;
//降序队列  大顶堆 less  大到小 默认
priority_queue <int,vector<int>,less<int> > pri_que;

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值