您的位置:首页 > 其它

STL中stack详解

2016-01-17 22:06 211 查看

stack

Stacks are a type of container adaptor, specifically designed to operate in a LIFO context (last-in first-out), where elements are inserted and extracted only from one end of the container.

The standard container classes vector, deque and list fulfill these requirements. By default, if no container class is specified for a particular stack class instantiation, the standard container deque is used.

C++ STL 的堆栈泛化是直接通过现有的序列容器来实现的,默认使用双端队列deque的数据结构,当然,可以采用其他线性结构(vector 或 list等),只要提供堆栈的入栈、出栈、栈顶元素访问和判断是否为空的操作即可。由于堆栈的底层使用的是其他容器,因此,堆栈可看做是一种适配器,将一种容器转换为另一种容器(堆栈容器)。

stack

Member functions
构造器constructor

empty

top

push

pop

size

swap

Member functions

构造器(constructor)

Constructs a stack container adaptor object.

std::deque<int> mydeque (3,100);          // deque with 3 elements
std::vector<int> myvector (2,200);        // vector with 2 elements

std::stack<int> first;                    // empty stack using deque(default)
std::stack<int> second (mydeque);         // stack initialized to copy of deque

std::stack<int,std::vector<int> > third;  // empty stack using vector
std::stack<int,std::vector<int> > fourth (myvector);


empty

Returns whether the stack is empty: i.e. whether its size is zero.

判断栈是否为空

top

Returns a reference to the top element in the stack.

Since stacks are last-in first-out containers, the top element is the last element inserted into the stack.

获取栈顶的元素,根据先入先出原则,获得最后压入栈中的元素

push

Inserts a new element at the top of the stack, above its current top element. The content of this new element is initialized to a copy of val.

将一个元素压入栈中,作为一个新的栈顶

pop

Removes the element on top of the stack, effectively reducing its size by one.

The element removed is the latest element inserted into the stack, whose value can be retrieved by calling member stack::top.

弹出栈顶元素

// stack::push/pop/empty/pop
#include <iostream>       // std::cout
#include <stack>          // std::stack

int main ()
{
std::stack<int> mystack;

for (int i=0; i<5; ++i) mystack.push(i);

std::cout << "Popping out elements...";
while (!mystack.empty())
{
std::cout << ' ' << mystack.top();
mystack.pop();
}
std::cout << '\n';

return 0;
}


Output:

Popping out elements… 4 3 2 1 0

size

Returns the number of elements in the stack.

获得栈中元素的个数

swap

Exchanges the contents of the container adaptor (*this) by those of x.

交换两个栈

// stack::swap
#include <iostream>       // std::cout
#include <stack>          // std::stack

int main ()
{
std::stack<int> foo,bar;
foo.push (10); foo.push(20); foo.push(30);
bar.push (111); bar.push(222);

foo.swap(bar);

std::cout << "size of foo: " << foo.size() << '\n';
std::cout << "size of bar: " << bar.size() << '\n';

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: