Stack implementation with constructor : Your stack « Data Types « C++ Tutorial






#include <iostream>
#include <assert.h>
using namespace std;
class ch_stack {
public:
   explicit ch_stack(int size): max_len( size), top(EMPTY)
   { assert(size > 0);s = new char[size]; assert(s != 0);}
   ch_stack();
   ch_stack(const ch_stack& str);
   ch_stack(int size, const char str[]);
  ~ch_stack() { delete []s; }
   void  reset() { top = EMPTY; }
   void  push(char c) { s[++top]= c; }
   char  pop() { return s[top--]; }
   char  top_of() const { return s[top]; }
   bool  empty() const { return (top == EMPTY); }
   bool  full() const { return (top == max_len - 1); }
private:
   enum  { EMPTY = -1 };
   char*  s;              
   int    max_len;
   int    top;
};

//default constructor for ch_stack
ch_stack::ch_stack():max_len(100),top(EMPTY)
{
   s = new char[100];
   assert(s != 0);
}

//domain transfer
ch_stack::ch_stack(int size, const char str[]):
   max_len(size)
{
   int i;
   assert(size > 0);
   s = new char[size];
   assert(s != 0);
   for (i = 0; i < max_len && str[i] != 0; ++i)
      s[i] = str[i];
   top = --i;
}

//Copy constructor for ch_stack of characters
ch_stack::ch_stack(const ch_stack& str):
   max_len(str.max_len),top(str.top)
{
   s = new char[str.max_len];
   assert(s != 0);
   memcpy(s, str.s, max_len);
}

int cnt_char(char c, ch_stack s)
{
   int  count = 0;

   while (!s.empty())
      count += (c == s.pop());
   return count;
}

int main()
{
   ch_stack  typea(100);  
   ch_stack  typeb;       
   ch_stack  typec(50, "this is a test");  
   ch_stack  typed(typec);
   char reverseline[200];
   char a [30] = {"aaaa"};
   char b [40] = {"bbbb"};
   int  i = 0;

   cout << cnt_char('a', typec) << endl;

   typea.reset();

   while (a[i])
      if (!typea.full())
    typea.push(a[i++]);

   i = 0;
   while (!typea.empty())
      reverseline[i++] = typea.pop();
   reverseline[i] = '\0';
   cout << reverseline;

   i = 0;
   while (b[i])
      if (!typeb.full())
    typeb.push(b[i++]);

   i = 0;
   while (!typeb.empty())
      reverseline[i++] = typeb.pop();
   reverseline[i] = '\0';
   cout << reverseline;

   i = 0;
   while (!typec.empty())
      reverseline[i++] = typec.pop();
   reverseline[i] = '\0';
   cout << reverseline;
   i = 0;

   while (!typed.empty())
      reverseline[i++] = typed.pop();
   reverseline[i] = '\0';
   cout << reverseline;
}








2.41.Your stack
2.41.1.Declare your own class stack
2.41.2.Generic stack
2.41.3.generic stack implementation
2.41.4.a stack as a class
2.41.5.Stack implementation with constructor