But I did not see any guarantee for this, that is, clearing the internal vector will be the same as calling pop() when priority_queue is not empty.
Because it is not the same thing. A std::priority_queue is a specially designed container adapter that organizes things according to strict weak orders. If you do not specify the type of container that the queue will have (which you do not see in the example), then the default type is std::vector .
Therefore, calling pop() on a non-empty priority queue will remove the top element from the queue, when clear() called in the base container, it will remove all elements from the queue, not just the topmost one.
Although I know other ways to clean it, such as swap or assign it using an empty priority, I think that if this code can work well, it will be more efficient, since the allocated memory in the vector will be reused. So I wonder, is this code portable or not always working?
According to the reference, the base member object c is protected, so access to how you should be guaranteed in different compilers, i.e. call this->c.clear(); It must be portable (by analogy, it works on g++ 4.2.1 in the old version of OpenBSD).
As for efficiency, this will depend somewhat. Doing something like this->c.clear(); vs. q = priority_queue <int>(); may differ from memory usage or complexity, although you will have to test it on different platforms to verify. However, do something like this->c.clear(); vs. while(!q.empty()) { q.pop(); } while(!q.empty()) { q.pop(); } will be more efficient.
In terms of memory efficiency, the priority queue pop function calls the base containers pop_back , and neither pop_back and clear affect the underlying capacity vector, so there really is no "saving"; although at the same time you can resize the vector to increase / decrease the capacity if you have a certain need.
Just remember that the pop priority queue function calls the underlying pop_back containers, and calling pop_back in an empty container is an undefined behavior .
Hope this helps.