Search code examples
c++iteratorpriority-queue

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.


Solution

  • 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;
        }
    }