本文介绍了有效地清空priority_queue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我想使用一个总是允许我检索最大元素的数据结构(例如来自STL)。 (我想推入元素,并删除 最大,推进其他元素等等。)似乎是 的priority_queue,STL可以正常工作。但是在某些时候,我已经完成了(即使这个队列不是空的,但是你想要扔掉剩下的元素)。它似乎是,我必须这样做: while(!Q.empty())Q.pop(); 其他类提供resize()或clear(),我猜这比使用while循环更有效。更有效。但是,这些函数不是 可用于priority_queue。有任何想法吗?提前感谢您的帮助。 Jan 解决方案 template< typename T> void makeEmpty(std :: priority_queue< T>& q) { std :: priority_queue< Tempty; std :: swap(q,空); } 当然,您需要衡量度量指标。 - 答:因为它弄乱了人们通常阅读文字的顺序。 问:为什么会这样是坏事吗? A:热门发布。 问:usenet和电子邮件中最烦人的是什么? 我可能会遗漏一些东西,但由于你总是想获得 最大的元素,我猜一个集合和一个运算符<对于你的元素类型 会给你你需要的东西。您可以使用rbegin()或begin()将 转到最后一个元素,具体取决于您的运算符<按顺序排列元素 ,升级或降序。 问候, - NeyAndrédeMello Zunino http://blog.zunino。 eti.br/ Alf P. Steinbach给了你一个很好的答案。另一个想法是使用一个 不同的容器并在其上调用std :: make_heap(),但始终保持堆属性的效率可能低于仅使用 优先队列。 - Marcus Kwok 将''无效'替换为'' 'net''回复 I would like to use a data structure (e.g. from the STL) that always allowsme to retrieve the largest element. (I want to push in elements, and removethe largest, push in further elements, etc.) It seems a priority_queue fromthe STL would work fine. However at some point, I am finished (even thoughthe queue is not empty) and want to throw away the rest of the elements. Itseems, I have to do this using: while (!Q.empty()) Q.pop(); Other classes offer a resize() or a clear() and my guess that this is muchmore efficient than using a while-loop. However, these functions are notavailable for a priority_queue. Any ideas? Thanks in advance for any help. Jan 解决方案 template< typename T >void makeEmpty( std::priority_queue<T>& q ){std::priority_queue<Tempty;std::swap( q, empty );} Of course, you need to measure measure measure. --A: Because it messes up the order in which people normally read text.Q: Why is it such a bad thing?A: Top-posting.Q: What is the most annoying thing on usenet and in e-mail?I might be missing something, but since you always wish to obtain thelargest element, I guess a set and an operator< for your element typewould give you what you need. You might use rbegin() or begin() to getto the last element, depending on whether your operator< sorts elementsin ascending or descending order, respectivelly. Regards, --Ney André de Mello Zunino http://blog.zunino.eti.br/Alf P. Steinbach gave you a good answer. Another idea is to use adifferent container and call std::make_heap() on it, but consistentlymaintaining the heap property may be less efficient than just using thepriority queue. --Marcus KwokReplace ''invalid'' with ''net'' to reply 这篇关于有效地清空priority_queue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-23 18:31