Click here to Skip to main content
15,885,767 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone, I'd like to clear a priority_queue object ,but it doesn't has the "clear" member function.
I'd rather not to pop all the members of the queue one by one because it may cost lots of time.
What can I do with it?

P.S.
My English is poor, I hope it I had described it clearly enough. Thanks a lot.
Posted

You can declare your own class this way:

C++
template <class Type>
class my_priority_queue
{
private:
   std::priority_queue<Type>* m_pQueue;

public:
   my_priority_queue()
   {
      m_pQueue = new std::priority_queue<Type>;
   }

   ~my_priority_queue()
   {
      delete m_pQueue;
   }

   bool empty() const
   {
      return m_pQueue->empty();
   }

   void pop()
   {
      m_pQueue->pop();
   }

   void push(const Type& _Val)
   {
      m_pQueue->push(_Val);
   }

   std::priority_queue<Type>::size_type size() const
   {
      return m_pQueue->size();
   }

   std::priority_queue<Type>::value_type& top() const
   {
      return m_pQueue->top();
   }

   void clear()
   {
      delete m_pQueue;
      m_pQueue = new std::priority_queue<Type>;
   }
};
 
Share this answer
 
v2
Comments
LieDragon 28-Jul-10 1:16am    
Thank you very much. In fact, I just want to delete all the members in the queue. So assign a empty queue to the object is enough. Just like the method you use in the "clear" function.
After all, Thank you all the same.
Simple answer is don't clear it!

priority_queues are designed to have stuff inserted in and sorted in priority order. They not designed to have stuff removed from them, well, except by yanking stuff off the front. If you want to clear it then bin the object and start again:

q = std::priority_queue<int>();</int>


Failing that you could always just repeatedly pop stuff off the queue unitl it's empty:

while( !q.empty() ) q.pop();


For me the first way is a lot cleaner but YMMV.

Cheers,

Ash

PS: I wouldn't worry about the costs of the second method. There's no reason why you can't implement pop to take hardly any time at all, just enough to destruct the element.
 
Share this answer
 
v2
Comments
LieDragon 28-Jul-10 1:19am    
Yeah, maybe I should not worry about the costs. In fact , I used the data structure in the ACM-ICPC programming. So I care about the effecient.
Now I konw I can just bin the object and start again.Thank you very much.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900