c++ - May I clear a priority_queue by clearing its underlying container? -


the following code inherits std::priority_queue , provides clear() calls internal std::vector's clear()

#include<iostream> #include<queue> using namespace std; template<class type> struct mypq :public priority_queue<type> {     void clear(){         this->c.clear();     } }; mypq<int>pq; int main() {     for(int i=0;i<10;++i)         pq.push(i);     pq.clear();     for(int j=-5;j<0;++j)         pq.push(j);     while (!pq.empty()){         cerr<<pq.top()<<endl;         pq.pop();     } } 

when tested g++, msvc++ , clang, produces expected output:

-1 -2 -3 -4 -5 

but haven't seen guarantee this, i.e. clearing internal vector same calling pop() when priority_queue isn't empty. although know other ways clear such swap or assign using empty priority_queue, think if code can work well, more efficient since allocated memory in vector reusable. wonder if code portable or won't work?

a question. while can't seem find strict guarantee correct method, there reasons think is.

for example, consider docs operator=:

copy assignment operator. replaces contents copy of contents of other. calls c = other.c;. (implicitly declared)

since other queue may of different size, means there no internal state dependent on size. moreover, implies assigning empty queue replaces container empty 1 , nothing else.

with in mind, , fact reasonable implementation of priority queue hardly need maintain state except size of queue, believe can safely assumed clearing underlying container valid way empty queue.


Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -