priority queue clear method

后端 未结 6 1883
我在风中等你
我在风中等你 2020-12-29 18:35

How do I delete all elements from a priority queue? That means how do I destroy a priority queue? advanced thanks for your answer. Is there any clear- or erase-like method

6条回答
  •  清歌不尽
    2020-12-29 19:05

    priority_queue doesn't have a clear method. It may be that this is for interface simplicity, or because it there may be situations in which elements must be destroyed in priority-order, making a generic clear function unsafe.

    Regardless, the following code block includes two functions to clear priority queues. The first works by building a temporary instance of a wrapper class around the priority_queue and then using this to access the underlying storage object, which is assumed to have a clear() method. The second works by replacing the existing priority_queue with a new queue.

    I use templating so that the functions can be recycled time and again.

    #include 
    #include 
    using namespace std;
    
    template 
    void clearpq(priority_queue& q) {
        struct HackedQueue : private priority_queue {
            static S& Container(priority_queue& q) {
                return q.*&HackedQueue::c;
            }
        };
        HackedQueue::Container(q).clear();
    }
    
    template 
    void clearpq2(priority_queue& q){
        q=priority_queue();
    }
    
    int main(){
        priority_queue testq, testq2;
    
        //Load priority queue
        for(int i=0;i<10;++i)
            testq.push(i);
    
        testq2=testq;
    
        //Establish it is working
        cout<

提交回复
热议问题