Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 22f5819

Browse files
template classes and template functions
1 parent 0d9b390 commit 22f5819

File tree

1 file changed

+77
-0
lines changed
  • Learn_CPP_Programming_Deep_Dive/Section 18 Template_functions_and_classes/Template_functions_and_classes

1 file changed

+77
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
#include <iostream>
2+
3+
using namespace std;
4+
5+
template <class T> // template class
6+
class Stack
7+
{
8+
private:
9+
T * stack;
10+
int top;
11+
int size;
12+
public:
13+
Stack(int sz) : top(-1), size(sz)
14+
{
15+
stack = new T[size];
16+
}
17+
18+
void push(T x);
19+
T pop();
20+
21+
void showTop()
22+
{
23+
cout<<"There are "<<top+1<<" elements in the stack"<<endl;
24+
}
25+
26+
};
27+
28+
template <class T> // template function
29+
void Stack<T>::push(T x)
30+
{
31+
if(top == size - 1)
32+
{
33+
cout<<"The stack is full, can not load it anymore."<<endl;
34+
}
35+
else
36+
{
37+
top++;
38+
stack[top] = x;
39+
}
40+
}
41+
42+
template <class T>
43+
T Stack<T>::pop()
44+
{
45+
T x = 0;
46+
47+
if ( top == -1)
48+
{
49+
cout<<"The stack is empty, can not take anything out of it"<<endl;
50+
}
51+
else
52+
{
53+
x = stack[top]; // store the last element into x variable
54+
cout<<"I removed this element from the stack \t"<<x<<endl;
55+
top --;
56+
}
57+
58+
return x;
59+
}
60+
61+
62+
int main(void)
63+
{
64+
Stack<int> s1(10);
65+
s1.push(12);
66+
s1.push(45);
67+
s1.push(46);
68+
s1.push(70);
69+
70+
s1.showTop();
71+
72+
int e = s1.pop();
73+
74+
s1.showTop();
75+
76+
return 0;
77+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /