[英]How is Stack implemented in STL?
I came across this: 我遇到了这个:
Standard C++ Containers 标准C ++容器
It triggered me the question, how are stacks implemented in STL? 这引发了我一个问题,即如何在STL中实现堆栈?
I am looking for a description similar to: 我正在寻找类似于以下内容的描述:
stack
is an adapter which uses another container for the underlying storage, and links the functions push
, pop
, emplace
etc. to the relevant functions in the underlying container. stack
是一个适配器,它使用另一个容器作为基础存储,并将push
, pop
, emplace
等功能链接到基础容器中的相关功能。
By default, std::stack
uses std::deque
as underlying container. 默认情况下,
std::stack
使用std::deque
作为基础容器。 But you can specify your own, eg std::stack<T, std::vector<T>> s;
但是您可以指定自己的,例如
std::stack<T, std::vector<T>> s;
. 。
For more details about this, see cppreference . 有关此的更多详细信息,请参见cppreference 。
std::stack
has a template parameter Container
, which is required to be a container that can store elements of type T
(that is to say, the type of the elements of the stack). std::stack
具有模板参数Container
,它必须是可以存储T
类型的元素(即,堆栈元素的类型)的容器。 This container is required to have back()
, push_back()
and pop_back()
functions, and the standard containers vector
, deque
and list
all satisfy the requirements. 该容器必须具有
back()
, push_back()
和pop_back()
函数,并且标准容器vector
, deque
和list
都满足要求。
So, whichever container type the user specifies, the resulting instantiation of std::stack
is a class which: 因此,无论用户指定哪种容器类型,
std::stack
的最终实例化都是一个类,该类:
Container<T>
(or something very similar if not literally a data member. I suppose it could probably be a private base class). Container<T>
的数据成员(或者如果不是字面意义上的数据成员,则非常相似。我想它可能是私有基类)。 push_back()
on the container whenever you call push()
on the stack. push()
时,都会在容器上调用push_back()
。 pop_back()
on the container whenever you call pop()
on the stack. pop()
时,都会在容器上调用pop_back()
。 Loosely speaking, std::stack<T>
is an object that wraps up an instance of std::deque<T>
, and hides most of deque
's functionality in order to present a simpler interface solely for use as a last-in-first-out (LIFO) queue. 松散地说,
std::stack<T>
是一个包装std::deque<T>
实例的对象,并隐藏了大多数deque
的功能,以便呈现一个更简单的接口, 仅用作后处理-先进先出(LIFO)队列。 Similarly std::queue
presents a FIFO queue. 同样,
std::queue
表示一个FIFO队列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.