#include <iostream>
#include <string>
#include <string.h>
#include "lstack.h"
using namespace std;
class Boring {
public:
Boring(double b) { m_boring = b; }
double get() { return m_boring; }
private:
double m_boring;
};
int main()
{
// Make a stack of integers.
Stack<int> is;
int n;
cout << "Enter integers to -1:" << endl << "> ";
while(cin >> n)
{
if(n == -1) break;
is.push(n);
cout << "> ";
}
cout << "Here are your " << is.size() << " integers." << endl;
while(!is.empty()) {
cout << is.pop() << " ";
}
cout << endl;
// Make a stack of strings.
Stack<string> ss;
string s;
cout << "Enter lines to eof:" << endl << "> ";
cin.clear();
getline(cin,s);
while(getline(cin,s))
{
ss.push(s);
cout << "> ";
}
cout << "\nHere are your " << ss.size() << " lines." << endl;
while(!ss.empty()) {
cout << ss.pop() << endl;
}
// Make a stack of Boring.
Stack<Boring> bor;
bor.push(Boring(2.45));
bor.push(Boring(-7.3));
bor.push(Boring(0.0));
cout << bor.size() << " boring objects on the boring stack." << endl;
Boring b(0);
while(bor.pop(b)) {
cout << b.get() << " ";
}
cout << endl;
// Note that this:
// b = bor.pop();
// does not compile. Any idea why?
}
This is just a sample user for the stack template class.
- When using the template stack, you must specify a value
for the template parameter, as in Stack<int> is;.
- Notice that we can make a stack of the basic int type.
This differs from Java, where only class types can be used as
template parameters. (One role of wrapper classes is to get
around this limitation.)
- As noted earlier, the first pop method assumes there is
a zero-argument constructor (called a “default constructor” in C++).
But the toy class Boring does not have such a constructor.
Interestingly, though, we can still make a boring stack,
Stack<Boring> bor;. The only restriction is that an attempt
to use the first pop, as bor.pop();, produces an error.
So the implicit restriction on T only causes problems when
the relevant code is invoked.