开发者

return the value in a stack - C++

开发者 https://www.devze.com 2022-12-08 09:41 出处:网络
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 n

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;
0

精彩评论

暂无评论...
验证码 换一张
取 消