一、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;