Thursday, June 28, 2012

Stack STL in C++


Stack
Stack is a data structure that follow the LIFO (last in first out). We can access it by using STL in C++.
First we have to use a header .
#include <stack>
Other accessing systems are given below . please read this carefully.

stack

<stack>
LIFO 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 the end of the container.

stacks are implemented as containers adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are pushed/popped from the "back" of the specific container, which is known as the top of the stack.

The underlying container may be any of the standard container class templates or some other specifically designed container class. The only requirement is that it supports the following operations:

Stacks are only accessed at their top. To be able to use STL stacks in a file of C++ source code or a header file add     at the beginning of the file.
Suppose that T is any type or class - say an int, a float, a struct, or a class, then
     stack<T> s;
declares a new and empty stack called s. Given s you can:
  • test to see if it is empty:
              s.empty()
  • find how many items are in it:
              s.size()
push a t of type T onto the top:
              s.push(t)
pop the top off :
                     s.pop()
get the top item of s
                      s.top()
             change the top item:
                      s.top() = expression.
        //Put characters from x onto the stack
                  for(int i=0; i<n; ++i)
                       s.push(x[i]);
        //take characters off of stack and put them back into x
                  for(int i=0; !s.empty(); ++i, s.pop())
                       x[i]=s.top();

Example


// constructing stacks
#include <iostream>
#include <vector>
#include <deque>
#include <stack>
using namespace std;
 
int main ()
{
  deque<int> mydeque (3,100);     // deque with 3 elements
  vector<int> myvector (2,200);   // vector with 2 elements
 
  stack<int> first;               // empty stack
  stack<int> second (mydeque);    // stack initialized to copy of deque
 
  stack<int,vector<int> > third;  // empty stack using vector
  stack<int,vector<int> > fourth (myvector);
 
  cout << "size of first: " << (int) first.size() << endl;
  cout << "size of second: " << (int) second.size() << endl;
  cout << "size of third: " << (int) third.size() << endl;
  cout << "size of fourth: " << (int) fourth.size() << endl;
 
  return 0;
}

Output:
size of first: 0
size of second: 3
size of third: 0
size of fourth: 2

No comments:

Post a Comment