删除前端元素并向min-heap添加新元素(std :: priority_queue)

时间:2017-02-09 15:24:24

标签: c++ algorithm

使用案例:我想为Linux程序实现一个非常有效的发送队列,在网络测试程序中每秒发送许多速率受限的大量UDP数据包流。目前,我使用了

priority_queue< pair<timespec, int>,
                std::vector<pair<timespec, int>>,
                std::greater<pair<timespec, int>> >

程序运行正常且速度很快。但是我希望能够在一个操作中弹出队列并添加一个新元素,即每个pop / emplace对只有一个重新堆积。否则,pop将重新堆积,然后emplace将再次直接重新堆积。

可以用std :: make_heap,std :: push_heap和std :: pop_heap完成吗?或者我必须自己动手?我当前的程序弹出后跟std :: priority_queue上的emplace,其成本为&lt; 2 * O(log(N))&#39;。

FWIW,目前的计划在这里:https://github.com/alapaa/timestamping/tree/send_queue

带队列的实际发件人是这个src文件: https://github.com/alapaa/timestamping/blob/send_queue/manysock/sender.cpp

2 个答案:

答案 0 :(得分:0)

使用deque作为容器,使用make_heap进行堆积。 - &GT; 使用vector作为容器,使用反向迭代器使用make_heap,然后向后推。 它会快一点。

vector<int> v{4,3,7,1,5};
make_heap(v.rbegin(), v.rend(), greater<int>());
for(auto& a : v) cout << a << ' ';
cout << endl;
q.pop_back();
q.push_back(9);
make_heap(v.rbegin(), v.rend(), greater<int>());
for(auto& a : q) cout << a << ' ';
cout << endl;

答案 1 :(得分:0)

很抱歉回答我自己的问题,但我在之前的SO搜索中找不到这个解决方案(看看jxh:s的答案):How to change max element in a heap in C++ standard library?