为什么std :: queue不支持clear()函数? [英] why std::queue doesn't support clear() function?
问题描述
我有这样的要求。对于函数,我获得作为数字流的输入。我的意思是,在每次调用中,函数继续使用单个数字调用。我使用队列存储数字流。只有当满足一些条件时,我需要处理一组收集的数字。如果条件不满足,我需要把所有的元素在队列中,然后开始存储新的数字。为了清空队列,我找不到clear()方法。所以我如下循环。
while(!q.empty())
q.pop
我在
获得了清除队列的高效算法http://stackoverflow.com/questions/709146/how-do-我的问题是:为什么队列不支持clear()函数?我的问题是:为什么队列不支持clear()函数?
当deque和vector支持clear()方法时,支持队列的技术难度是多少?
还是我上面的usecase非常罕见,因此不支持?
谢谢。
根据http://www.cplusplus.com/reference/stl/queue/ ,
队列被实现为容器适配器,它是使用特定容器类的封装对象作为其底层容器的类,提供一组特定的成员函数来访问它的元素。
这意味着队列使用已经存在的容器,并且只是作为FIFO队列的这个容器的接口。
这意味着队列不会被清除。如果您需要清除队列,这意味着您实际上需要使用不是队列的对象,因此您应该使用实际的底层容器类型,默认为deque。
I have requirement like this. For a function, i get input as a stream of numbers. I mean, function keeps on getting called with single number in each call. I am using queue for storing stream of numbers. I need to process a collected set of numbers only when some condition is satisfied. If condition is not satisfied i need to throw all the elements in the queue and then start storing new numbers in that. For emptying the queue, i couldn't find clear() method. So i am looping like below.
while(!q.empty())
q.pop();
I got efficient algorithm for clearing queue at
http://stackoverflow.com/questions/709146/how-do-i-clear-the-stdqueue-efficiently
My question is: Why queue doesn't support clear() function ?
When deque and vector are supporting clear() method, what is the technical difficulty in supporting it for queue ?
Or is my above usecase very rare and hence not supported ? Thank you.
According to http://www.cplusplus.com/reference/stl/queue/,
queues are implemented as containers adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access it elements.
which means that the queue uses an already existing container, and is just really is an interface to this container as a FIFO queue.
This means queues are not meant to be cleared. If you need to clear a queue, this means you actually need to use an object that is not a queue, and therefore you should instead use the actual underlying container type, being a deque by default.
这篇关于为什么std :: queue不支持clear()函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!