Mail Archives: djgpp/1997/11/11/08:31:06
Charles:
Templates are good. Templates are good. Keep saying this, and the following
will be easier
to live with:
An STL stack<class T> is a "container adapter". What's that? Well, it's a
template class
which adapts a container template class, adding some functionality. In the
case of
stack, the added functionality is largely the push/pop functions. But the
stack template
just ADDS these functions to a container template class like deque, list or
vector.
I think you want a stack<deque<operator> >, not a stack<operator>, since
your operator type
isn't a container template class.
Here's what I did to your example to get it working (My comments identify
the changes):
// Add this:
#include <deque>
#include <stack>
#include <_string.h>
// Change names as yours are used in lang/cxx/function.h
enum operators { leftparen, add, subtract, multiply, divide};
String opString(operators theOp)
{
switch (theOp) {
// Change names here too, of course.
case add: return " + ";
case subtract: return " - ";
case multiply: return " * ";
case divide: return " / ";
case leftparen: return " [ ";
default: return "\0";
}
}
// Insert this so gcc instantiates deque<operators>
// (see info gcc, under "Template Instantiation", for details).
template class deque<operators>;
// Change the second parameter to be a stack<deque<operators> >
void processOp
(operators theOp, stack<deque<operators> > & opStack, String & result)
{
// pop stack while operators have higher precedence
while ((! opStack.empty()) && (theOp < opStack.top()))
{
result += opString(opStack.top());
opStack.pop(); // You had opString.
}
opStack.push(theOp);
}
// I added this to test:
int main(void)
{
stack< deque<operators> > myStack;
String myResult;
operators myOp(leftparen);
myStack.push(add);
myStack.push(leftparen);
myStack.push(subtract);
myStack.push(multiply);
myStack.push(divide);
processOp(myOp, myStack, myResult);
cout << myResult;
return 0;
}
Name this file "stack.cc".
Compile with "gcc -o stack stack.cc -lstdcx -lgpp"
I haven't taken time to consider what you're doing here, so perhaps list or
vector is
better than deque. I didn't know what output to expect so I can't validate
the
myResult value either.
But that should help with the STL.
--
John Bodfish
bodfish AT als DOT ameritech DOT com
- Raw text -