如何访问我的优先队列中的 10 个最大数字

How to access 10 largest numbers inside my priority queue

假设我的优先级队列中有 30 个随机数,如何在对它们进行排序后仅访问特定数量的最大值。例如,我需要在我的优先级队列中打印前 10 个最大的数字

因此,您将所有随机数推入队列:好的。然后您访问最上面的数字,并在访问时将它们从列表中删除:

const int desired_numbers = 10;
for(int i=0; i<desired_numbers; i++)
{
    int t = mypq_decreasing.top();
    mypq_decreasing.pop();

    mylist.remove(t); //remove from original list
}

在此之后,队列和列表都包含所有随机数,但十个(因为在每次访问顶部之后,您将顶部弹出队列并从列表中删除元素)。

如果我对你的问题理解正确,你想通过优先级队列访问大小为 30 的列表中的 X 个最大数字,你可以这样做。

template<typename T>
struct my_less;
//Specialization in order to dereference a pointer before doing the comparison
template<typename T>
struct my_less<T*>
{
  void operator (T* lhs, T* rhs){
   return (*lhs)<(*rhs);
  }
}
using lookupPriorityQueue=std::priority_queue<int*,std::vector<int*>,my_less<int*>>;
lookupPriorityQueue p;
for(auto& element: your_list_of_ints)
{
   p.push(&element);
}
for(auto i=0;i!=10;++i,p.pop())
{
  std::cout<<*(p.top())<<"\n";
}

使用这种方法,您不必将所有内容都复制到 priority_queue 即可找出前 X 个元素。 但是你应该非常小心,因为我们正在存储指向元素的指针,如果 priority_queue 超过列表,我们将访问无效内存

看来你不需要priority_queue,只需要使用算法:

std::vector<int> numbers /*= */;

std::partial_sort(numbers.begin(), numbers.begin() + 10, std::greater<>());

for (std::size_t i = 0; i != 10; ++i)
{
    std::cout << numbers[i] << " ";
}