Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,994 questions

51,939 answers

573 users

How to write template class for a stack in c++

1 Answer

0 votes
#include <iostream>

using std::cout;
using std::endl;

#define SIZE 5

template <class T>
class Stack {
private:
	int total;  
	int top;
	T *p;
public:
	Stack(int = SIZE);
	~Stack() { delete[] p; }
	int push(const T&);
	int pop(void);  
	int isEmpty() const { return top == -1; }
	int isFull()  const { return top == total - 1; }
	void print(void);
};

template <class T>
Stack<T>::Stack(int _total)
{
	total = _total > 0 ? _total : SIZE;
	top = -1;  
	p = new T[total];
}

template <class T>
int Stack<T>::push(const T &value)
{
	if (!isFull())
	{
		p[++top] = value;
		return 1;  
	}
	return 0;  
}

template <class T>
int Stack<T>::pop(void)
{
	if (!isEmpty())
	{
		p[top--] = 0;
		return 1;  
	}
	return 0; 
}

template <class T>
void Stack<T>::print(void)
{
	for (int i = 0; i < total; i++)
		cout << p[i] << " ";
	cout << endl;
}

int main()
{
	typedef Stack<float> floatStack;
	typedef Stack<int> intStack;

	floatStack fs(3);
	float f = 3.15;
	while (fs.push(f))
		f += 0.5;
	fs.print();
	fs.pop();
	fs.print();

	intStack is;
	int n = 2;
	while (is.push(n))
		n *= 2;
	is.print();
	is.pop();
	is.pop();
	is.print();

	return 0;
}


/*
run:

3.15 3.65 4.15
3.15 3.65 0
2 4 8 16 32
2 4 8 0 0

*/

 



answered Mar 13, 2018 by avibootz

Related questions

1 answer 225 views
2 answers 222 views
1 answer 199 views
1 answer 190 views
1 answer 162 views
1 answer 118 views
...