优先队列

priority_queue
默认大顶堆
小顶堆

include

include

using namespace std;

void max_k_num()
{
int source_data[10] = {3, 5, 8, 1, 10, 2, 9, 15, 13, 16};
int k = 5;
// 小根堆
priority_queue<int, vector, greater> q;
for (auto n : source_data)
{
if (q.size() == k)
{
if (n > q.top())
{
q.pop();
q.push(n);
}
}
else
q.push(n);
}

while (!q.empty()) 
{
    cout << q.top() << endl;
    q.pop();
}

}

posted @ 2024-04-19 21:59  niubuniu  阅读(1)  评论(0编辑  收藏  举报