A generic stack with size 10 : generic stack « template « C++ Tutorial

Home
C++ Tutorial
1.Language Basics
2.Data Types
3.Operators statements
4.Array
5.Development
6.Exceptions
7.Function
8.Structure
9.Class
10.Operator Overloading
11.Pointer
12.File Stream
13.template
14.STL Introduction
15.string
16.vector
17.list
18.bitset
19.set multiset
20.valarray
21.queue stack
22.deque
23.map multimap
24.STL Algorithms Modifying sequence operations
25.STL Algorithms Non modifying sequence operations
26.STL Algorithms Binary search
27.STL Algorithms Sorting
28.STL Algorithms Merge
29.STL Algorithms Min Max
30.STL Algorithms Iterator
31.STL Algorithms Heap
32.STL Algorithms Helper
C / ANSI-C
C Tutorial
C++
Visual C++ .NET
C++ Tutorial » template » generic stack 
13.16.2.A generic stack with size 10
#include <iostream>
using namespace std;

const int SIZE = 10;

template <class StackType> class stack {
  StackType stck[SIZE];
  int tos;

public:
  stack() {
     tos = 0;
  }
    void push(StackType ob)
    {
      if(tos==SIZE) {
        cout << "Stack is full.\n";
        return;
      }
      stck[tos= ob;
      tos++;
    }

    StackType pop()
    {
      if(tos==0) {
        cout << "Stack is empty.\n";
        return 0// return null on empty stack
      }
      tos--;
      return stck[tos];
    }
};

int main() {
  stack<char> s1, s2;

  s1.push('a');
  s2.push('x');
  s1.push('b');
  s2.push('y');
  s1.push('c');
  s2.push('z');

  for(int i=0; i<3; i++)
     cout << "Pop s1: " << s1.pop() << "\n";
  for(int i=0; i<3; i++)
     cout << "Pop s2: " << s2.pop() << "\n";

  stack<double> ds1, ds2;

  ds1.push(1.1);
  ds2.push(2.2);
  ds1.push(3.3);
  ds2.push(4.4);
  ds1.push(5.5);
  ds2.push(6.6);

  for(int i=0; i<3; i++)
     cout << "Pop ds1: " << ds1.pop() << "\n";
  for(int i=0; i<3; i++)
     cout << "Pop ds2: " << ds2.pop() << "\n";

  return 0;
}
Pop s1: c
Pop s1: b
Pop s1: a
Pop s2: z
Pop s2: y
Pop s2: x
Pop ds1: 5.5
Pop ds1: 3.3
Pop ds1: 1.1
Pop ds2: 6.6
Pop ds2: 4.4
Pop ds2: 2.2
13.16.generic stack
13.16.1.Generic Stack
13.16.2.A generic stack with size 10
13.16.3.template stack based on deque
13.16.4.Max size as the parameter for a generic stack
13.16.5.Generic stack based on vector
13.16.6.template string stack
13.16.7.Generic stack with deque
13.16.8.Use generic stack to store another container
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.