简体   繁体   中英

Priority Queues in c++

Is there a way to iterate over a priority queue in c++ ? My understanding is that they are more or less immutable and the only manipulation of the container is to the top element. I would like to be able to print out the contents of a priority queue but am unsure of how to even approach the problem.

The underlying container is a protected data member named c (see here for further details). Therefore you can always inherit from a std::priority_queue and export a couple of iterators over that container (if available).
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: inheriting from data structures in the std:: namespace is usually discouraged.
That being said, it works at least.


The code above works in C++14.
Below a slightly modified version that works also in C++11 as requested 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;
    }
}

Based on @skypjack's answer, here is a templated 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;
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM