int source_data[10] = {3, 5, 8, 1, 10, 2, 9, 15, 13, 16};
// 默认大根堆,实现由大到小排序
priority_queue<int> q;
for (auto n : source_data)
q.push(n);
while (!q.empty())
{
cout << q.top() << endl;
q.pop();
}
int source_data[10] = {3, 5, 8, 1, 10, 2, 9, 15, 13, 16};
int k = 6;//选最大的6个数从小到大排
// 小根堆
priority_queue<int, vector<int>, greater<int>> 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();
}
学习自用,未标明引用,欢迎讨论问题