1. 程式人生 > >STL中stack詳解

STL中stack詳解

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等),只要提供堆疊的入棧、出棧、棧頂元素訪問和判斷是否為空的操作即可。由於堆疊的底層使用的是其他容器,因此,堆疊可看做是一種介面卡,將一種容器轉換為另一種容器(堆疊容器)。

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;
}