Priority Queues in C ++

Is there a way to iterate over a priority queue in C ++? I understand that they are more or less immutable, and the only manipulation of the container is the top element. I would like to be able to print priority queue contents, but I'm not sure how to solve the problem.

+5
source share
2 answers

The base container is a protected data item named c (see here for more details). Therefore, you can always inherit from std::priority_queue and export a couple of iterators over this container (if any).
As a minimal working example:

 #include<queue> #include<iostream> struct MyPriorityQueue: std::priority_queue<int> { auto begin() const { return c.begin(); } auto end() const { return c.end(); } }; int main() { MyPriorityQueue pq; pq.push(0); pq.push(1); for(auto &v: pq) { std::cout << v << std::endl; } } 

Note: inheritance from data structures in the std:: usually discouraged.
That being said, it works as a minimum.


The code above works in C ++ 14.
Below is a slightly modified version that also works in C ++ 11, as noted in the comments:

 #include<queue> #include<iostream> struct MyPriorityQueue: std::priority_queue<int> { decltype(c.begin()) begin() const { return c.begin(); } decltype(c.end()) end() const { return c.end(); } }; int main() { MyPriorityQueue pq; pq.push(0); pq.push(1); for(auto &v: pq) { std::cout << v << std::endl; } } 
+6
source

Based on @skypjack's answer, this is a boilerplate version:

 #include<queue> #include<iostream> template<class T, class C = vector<T>, class P = less<typename C::value_type> > struct MyPriorityQueue : std::priority_queue<T,C,P> { typename C::iterator begin() { return std::priority_queue<T, C, P>::c.begin(); } typename C::iterator end() { return std::priority_queue<T, C, P>::c.end(); } }; int main() { MyPriorityQueue<int> pq; pq.push(0); pq.push(1); for (auto &v : pq) { std::cout << v << std::endl; } } 
+2
source

Source: https://habr.com/ru/post/1263478/


All Articles