Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I had the same problem, where I wanted to iterate over a priority queue without dequeuing (hence destroying my queue). I made it work for me by recasting my priority_queue pointer to a pointer to a vector (as my <code>priority_queue</code> uses vector as its container). Here is how it looks like:</p> <pre><code>class PriorityQueue { private: class Element { int x; //Other fields ... .. //Comparator function bool operator()(const Element* e1, const Element* e2) const { // Smallest deadline value has highest priority. return e1-&gt;x &gt; e2-&gt;x; } }; // Lock to make sure no other thread/function is modifying the queue // Ofcourse we can do our operation w/o lock. if we are sure what is happening in other functions pthread_mutex_t lock; std::priority_queue&lt;Element*, std::vector&lt;Element*&gt;, Element&gt; pq; public: PriorityQueue(); ~PriorityQueue(); //print the all the elements of the queue void print_queue_elements() { std::vector&lt;PriorityQueue::Element*&gt; *queue_vector; //Acquire the lock pthread_mutex_lock(&amp;lock); //recast the priority queue to vector queue_vector = reinterpret_cast&lt;std::vector&lt;PriorityQueue::Element*&gt; *&gt;(&amp;pq); for(std::vector&lt;PriorityQueue::Element*&gt;::iterator it = (*queue_vector).begin(); it != (*queue_vector).end(); it++) { //Assuming Element class has string function printf("My Element %s", (*it)-&gt;string); //other processing with queue elements } //Release the lock pthread_mutex_unlock(&amp;lock); } //other functions possibly modifying the priority queue ... .. . }; </code></pre> <p>Now since I am using reinterpret_cast, people can argue about type-safety. But in this case I am sure about all other functions accessing/changing the queue (all of which are safe).. and I feel this is a much better way than copying the content of whole queue to some other container.</p> <p>I was actually expecting <code>static_cast</code> to work.. as priority_queue is adaptor over container (vector in our case), but it doesnt and I had to use <code>reinterpret_cast</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload