有人知道为什么 std::queue、std::stack 和 std::priority_queue 不提供 clear()
成员函数吗?我必须像这样伪造一个:
std::queue<int> q;
// time passes...
q = std::queue<int>(); // equivalent to clear()
IIRC, clear()
由所有可以作为底层容器的东西提供。是否有充分的理由不让容器适配器提供它?
最佳答案
嗯,我认为这是因为 clear
不被视为对队列、priority_queue 或堆栈的有效操作(顺便说一下,deque 不是适配器,而是容器)。
The only reason to use the container adaptor queue instead of the container deque is to make it clear that you are performing only queue operations, and no other operations. (from the sgi page on queue)
所以当使用队列时,你所能做的就是推送/弹出元素;清除队列可以看作是对 FIFO 概念的违反。因此,如果您需要清除队列,也许它并不是真正的队列,您最好使用双端队列。
不过,这样的概念有点狭隘,我觉得像你这样排长队就够公平了。
关于c++ - 为什么标准的 C++ 容器适配器不提供明确的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/493774/