【发布时间】:2019-10-14 13:08:26
【问题描述】:
我正在尝试查找动态填充的列表中的前 n 个项目。我认为优先队列将是解决此问题的好方法。因为我只需要前 n 个,所以除了我的计算所需的“n”个项目之外,存储任何东西都没有意义。我在 boost 库中找不到任何似乎能够为优先级队列设置限制的东西
我尝试使用 reserve(element_count) 函数。文档说该函数用于“为 element_count 元素保留空间”。但这并没有像我想象的那样奏效
这是我正在编写的一些示例代码。不过,这不是用例。
int main()
{
int maxSize = 2; // Priority Queue (pq) is expected to hold a maximum of 2 elements at any time
boost::heap::priority_queue<int> pq; // Declaration
pq.reserve(maxSize); // I assumed this would reserve space only for 2 elements and anything more would over write the existing ones based on comparison
pq.push(3);
pq.push(2);
pq.push(1); // Push should fail
cout << "Size = " <<pq.size() << " Max Size = " << (int)pq.max_size();
for (int i=0; i<maxSize; i++)
{
int a = pq.top();
pq.pop();
cout << a <<"\n";
}
return 0;
}
我预计结果是:
尺寸 = 2 最大尺寸 = 2
3
2
但我得到的是:
尺寸 = 3 最大尺寸 = -1
3
2
我错过了什么?
【问题讨论】:
标签: c++11 boost priority-queue