In: Computer Science
Give an example of a program that uses the nongeneric version of a class from the STL and the equivalent program that uses the generic version. How do the two implementations differ? Why is having the syntax of generics better?
STL Without GENERICS:
#include <iostream>
#include <stack>
using namespace std;
void displayStack(stack <int> s) {
while (!s.empty())
{
cout << " " << s.top();
s.pop();
}
cout << endl;
}
int main ()
{
stack <int> s;
s.push(10);
s.push(30);
s.push(20);
s.push(5);
s.push(1);
cout << "The stack is : ";
displayStack(s);
cout << "\ns.size() : " << s.size();
cout << "\ns.top() : " << s.top();
cout << "\ns.pop() : ";
s.pop();
displayStack(s);
return 0;
}
STL With GENERICS
#include <iostream>
#include <stack>
using namespace std;
template <class T>
void displayStack(stack <T> s) {
while (!s.empty())
{
cout << " " << s.top();
s.pop();
}
cout << endl;
}
void intStack() {
stack<int> s;
s.push(10);
s.push(30);
s.push(20);
s.push(5);
s.push(1);
cout << "The stack is : ";
displayStack(s);
cout << "\ns.size() : " << s.size();
cout << "\ns.top() : " << s.top();
cout << "\ns.pop() : ";
s.pop();
displayStack(s);
}
void charStack() {
stack<char> s;
s.push('A');
s.push('B');
s.push('C');
s.push('D');
s.push('E');
cout << "The stack is : ";
displayStack(s);
cout << "\ns.size() : " << s.size();
cout << "\ns.top() : " << s.top();
cout << "\ns.pop() : ";
s.pop();
displayStack(s);
}
int main ()
{
intStack();
charStack();
return 0;
}
You can clearly see from the code that the same displayStack function could be used to display the content of both int and char stack. Without generics, we would have to write separate methods for each type.