简体   繁体   English

如何在STL中实现Stack?

[英]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: 我正在寻找类似于以下内容的描述:

How is C++ std::vector implemented? C ++ std :: vector如何实现?

What really is a deque in STL? STL中真正的双端队列是什么?

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是一个适配器,它使用另一个容器作为基础存储,并将pushpopemplace等功能链接到基础容器中的相关功能。

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()函数,并且标准容器vectordequelist都满足要求。

So, whichever container type the user specifies, the resulting instantiation of std::stack is a class which: 因此,无论用户指定哪种容器类型, std::stack的最终实例化都是一个类,该类:

  • has a data member of type Container<T> (or something very similar if not literally a data member. I suppose it could probably be a private base class). 具有类型为Container<T>的数据成员(或者如果不是字面意义上的数据成员,则非常相似。我想它可能是私有基类)。
  • calls push_back() on the container whenever you call push() on the stack. 每当您在堆栈上调用push()时,都会在容器上调用push_back()
  • calls pop_back() on the container whenever you call pop() on the stack. 每当您在堆栈上调用pop()时,都会在容器上调用pop_back()
  • and so on. 等等。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM