如何有效地清除 C++ 中的堆栈?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40201711/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how can i clear a stack in c++ efficiently?
提问by Misbah Ahmad
I have a c++ stack named pages. As I have no clear() function to clear a stack, I wrote the following code:
我有一个名为 pages 的 C++ 堆栈。由于我没有 clear() 函数来清除堆栈,因此我编写了以下代码:
stack<string> pages;
//here is some operation
//now clearing the stack
while(!pages.empty())
pages.pop();
Now my question: is there a better efficient way to clear the stack? Thanks in advance.
现在我的问题是:有没有更有效的方法来清除堆栈?提前致谢。
采纳答案by v78
In general you can't clear copying containers in O(1) because you need to destroy the copies. It's conceivable that a templated copying container could have a partial specialization that cleared in O(1) time that was triggered by a trait indicating the type of contained objects had a trivial destructor.
通常,您无法清除 O(1) 中的复制容器,因为您需要销毁副本。可以想象,模板化复制容器可以具有在 O(1) 时间内清除的部分特化,该特化由指示所包含对象的类型具有简单析构函数的特征触发。
If you want to avoid loop.
如果你想避免循环。
pages=stack<std::string>();
or
或者
stack<std::string>().swap(pages);
回答by Ely
I don't think there is a more efficient way. A stack is a well defined data type, specifically designed to operate in a LIFO context, and not meant to be emptied at once.
For this you could use vector
or deque
(or list
), which are basically the underlying containers; a stack
is in fact a container adaptor. Please see this C++ Referencefor more information.
我认为没有更有效的方法。堆栈是一种定义明确的数据类型,专门设计用于在 LIFO 上下文中操作,并不意味着立即清空。为此,您可以使用vector
or deque
(or list
),它们基本上是底层容器;astack
实际上是一个容器适配器。有关更多信息,请参阅此C++ 参考。
If you don't have a choice, and you have to use stack, then there is nothing wrong with the way you do it. Either way, the elements have to be destroyed if they were constructed, whether you assign a new empty stack or pop all elements out or whatever.
如果你别无选择,你必须使用堆栈,那么你这样做的方式没有错。无论哪种方式,如果元素被构造,则必须销毁它们,无论是分配新的空堆栈还是弹出所有元素或其他。
I suggest to use a vector
instead; it has the operations you need indeed:
我建议使用 avector
代替;它具有您确实需要的操作:
- size (or resize)
- empty
- push_back
- pop_back
- back
- clear
- 大小(或调整大小)
- 空的
- 推回
- pop_back
- 背部
- 清除
It is just more convenient, so you can use the clear
method. Not sure if using vector
is really more performant; the stack operations are basically the same.
它只是更方便,因此您可以使用该clear
方法。不确定 usingvector
是否真的更高效;堆栈操作基本相同。
回答by serget
What about subclassing std::stack and implementing a simple clear() method like this, accessing underlying container c ?
子类化 std::stack 并实现像这样的简单 clear() 方法,访问底层容器 c 怎么样?
public:
void clear() { c.clear(); }