I was doing some hacking today and found out that std::priority_queue does not have a clear()
member function. Are there any technical reasons as to why the standards committee may have left this out?
To be clear, I am aware that it is easy to work around this via assignment:
oldPQ = std::priority_queue<int>{};
This solution is less desirable because:
- It requires you to repeat the type - this does not continue to work under maintenance. As @chris pointed out below, you can simplify this if you're using the default constructor, but if you have a custom comparator, this may not be possible.
std::priority_queue
cannot be used in a templated function that expects aclear()
member function.- It is generally undesirable that it does not meet the common interface provided by the other containers. In particular, everything from
std::forward_list
tostd::unordered_map
tostd::string
hasclear()
. The only other exceptions I note are std::array, for which the semantics would not make sense, andstd::stack
andstd::queue
, for which the semantics are more questionable whenstd::deque
works without any extra effort.
One item that looks like an issue, but in practice needn't be:
Because the internal container used for std::priority_queue
is templated and may not have a clear()
member function of its own, this creates an interesting problem, in particular it raises the question of backward compatibility. This is a non-issue because:
- For internal containers that do not provide
clear()
, as long as nobody attempts to invokestd::priority_queue::clear()
, the code will continue to compile. - It may still be possible with SFINAE to provide the new interface (the clear member) by calling
clear()
on the internal container when it's available and by repeatedly popping if it is not.
It is my opinion that this is a defect in the C++ standard. Assuming a technical discussion does not provide a strong case for why this method is omitted, I intend to pursue the creation of a standards proposal.
Edit:
Seems this is being handled in-committee (note the last post): https://groups.google.com/a/isocpp.org/forum/?fromgroups#!searchin/std-discussion/clear/std-discussion/_mYobAFBOrM/ty-2347w1T4J