i try to write a project program about stack. i degined
In stack.h templates for stack, push and pop, and defined two stack objects one for integer and other for Float in main.cpp to get following types of output, but my but program does not compiles and give error. source coding files are:
stack.h
//stack.h
#pragma once
template <class T>
class Stack
{
public:
Stack(int = 10) ;
~Stack() { delete [] stackPtr ; }
int push(const T&);
int pop(T&) ; // pop an element off the stack
int isEmpty()const { return top == -1 ; }
int isFull() const { return top == size - 1 ; }
private:
int size ; // Number of elements on Stack
int top ;
T* stackPtr ;
} ;
//constructor with the default size 10
template <class T>
Stack<T>::Stack(int s)
{
size = s > 0 && s < 1000 ? s : 10 ;
top = -1 ; // initialize stack
stackPtr = new T[size] ;
}
// push an element onto the Stack
template <class T>
int Stack<T>::push(const T& item)
{
if (!isFull())
{
stackPtr[++top] = item ;
return 1 ; // push successful
}
return 0 ; // push unsuccessful
}
// pop an element off the Stack
template <class T>
int Stack<T>::pop(T& popValue)
{
if (!isEmpty())
{
popValue = stackPtr[top--] ;
return 1 ; // pop successful
}
return 0 ; // pop unsuccessful
}
main.cpp:
#include <iostream>
#include "stack.h"
using namespace std ;
int main(int argc, char *argv[])
{
typedef Stack<float> FloatStack ;
typedef Stack<int> IntStack ;
//declear two object of class stack one float other int
//cout << "Pushing elements onto fs" << endl ;
//cout << endl << "Stack Full." << endl<< endl << "Popping elements from fs" << endl ;
//cout << endl << "Stack Empty" << endl ;
FloatStack fs(5) ;
float f = 1.1 ;
cout << "Pushing elements onto fs" << endl ;
while (fs.push(f))
{ cout << f << ' ' ;
f += 1.1 ;
}
cout << endl << "Stack Full." << endl
<< endl << "Popping elements from fs" << endl ;
while (fs.pop(f))
cout << f << ' ' ;
cout << endl << "Stack Empty" << endl << endl ;
//cout << "Pushing elements onto is" << endl ;
// write ur code here
//cout << endl << "Stack Full" << endl<< endl << "Popping elements from is" << endl ;
//cout << endl << "Stack Empty" << endl ;
IntStack is ;
int i = 1.1 ;
cout << "Pushing elements onto is" << endl ;
while (is.push(i))
{ cout << i << ' ' ;
i += 1 ;
}
cout << endl << "Stack Full" << endl
<< endl << "Popping elements from is" << endl ;
while (is.pop(i)) cout << i << ' ' ;
cout << endl << "Stack Empty" << endl ;
system("PAUSE");
return 0;
}
/* output
Pushing elements onto fs
1.1 2.2 3.3 4.4 5.5
Stack Full.
Popping elements from fs
5.5 4.4 3.3 2.2 1.1
Stack Empty
Pushing elements onto is
1 2 3 4 5 6 7 8 9 10
Stack Full
Popping elements from is
10 9 8 7 6 5 4 3 2 1
Stack Empty
*/
<< moderator edit: added [co[u][/u]de][/co[u][/u]de]
tags >>