return the value in a stack - C++
I have the following defined:
Stack<ASTNode*>* data;
The way the class is defined, if I do data->push()
or data->pop()
, I directly push onto the stack or pop off the stack. To get the node at the top of the stack I would do data->peek()
. For testing purposes, I would like to print out the top node in the stack like this:
cout << "top of stack is... " << ? << endl;
I'm not sure what the syntax is or how to derefere开发者_如何学运维nce this.
thanks in advance, Hristo
The syntax you're looking for should be something like this:
cout << "top of stack is... " << *(data->peek()) << endl;
For this to work there needs to be an operator<<
defined for ASTNode
. If this isn't the case, you can define your own that would look like this:
std::ostream& operator<<(std::ostream &strm, const ASTNode &node) {
return strm << node.name << ": " << node.value;
}
It depends on how much information you need. If all you need is the address of the object on the top of the stack (might be enough for debugging, depends what you're doing I guess) the answer is as simple as:
cout << "top of stack is..." << data->peek() << endl;
If you need the object itself, just use:
cout << "top of stack is..." << *(data->peek()) << endl;
or
cout << "top of stack is..." << data->peek()->someIdentifyingMethod() << endl;
Assuming your ASTNode class has overloaded operator<<, it looks like you need:
cout << "top of stack: " << *(data->peek()) << endl;
精彩评论