I have a doubt with an exercise on stacks, whose code is the one you have below, what I want to ask is why the operands are unstacked , are they popped, before operating with them? I mean this:
const int r_op = stack_.top();
stack_.pop(); // aqui está mi duda, se le hace un pop antes de operar con él?
And another question, is it supposed that to stack an element you have to resort to push, is that different from doing this? const int r_op = stack_.top();
If you could explain that to me. Thank you
void operate(char operador){ //operando derecha,izquierda, lo mete en la pila, cuando terminamos, con pop sacas lo que hay en la pila, Y QUÍ ES DONDE SE OPERA CON ELLOS, SE GUARDA EL 4 EN R_OP, Que ya de por sí está en el top, luego se le elimina, se le hace un pop, y el 3 pasa a ser el top de la pila, se guarda en left_op, y luego se elimina de la pila con pop
const int r_op = stack_.top(); //añadido, right es el primer elemento en salir en la pila, recuerda el símil de la caja, operamos de izquierda a derecha
stack_.pop();
const int l_op = stack_.top();
stack_.pop();
int result = 0;
switch (operador) {
case '+': result = l_op + r_op; break;
case '-': result = l_op - r_op; break;
case '*': result = l_op * r_op; break;
case '/': result = l_op / r_op; break;
/* ... */
}
stack_.push(result);
}
Thank you
Believe it or not, your question is agnostic of the language you are using.
In your case, note that this class uses
top
to see the first element that is on the stack,pop
to remove it andpush
to insert an element. So, sincepop
the case you're showing doesn't return the item you popped, you must use firsttop
to see what's on the top of the stack. andpop
then to pop it out (because a stack cannot be traversed).your second question doesn't make sense
Makes you save what's at the top of the stack to r_op. with
push
you push something on the stack.Another note : I don't know why you define the variables you pop off the stack as const. Some expert will surely be able to explain you better, but those are not constants.
It remains to explain the context where this code is used, but I still deduce that it is part of a compiler or interpreter and the stack is used to solve arithmetic operations. The idea is that when the function/method
void operate()
is called, the two operands are stored on the top of the stack, for example 3 down and 4 up that came from an expression such as:Since the idea is to solve the expression, the two operands must be removed from the stack and replaced by the result (7=3+4). I understand that in this stack implementation, the primitive
top()
returns the value that is at the top of the stack but does not remove it, and for that the primitive is neededpop()
. Finallypush(result)
, what it does is put the result of the operation on the top of the stack (replacing the two operands that were already eliminated), that is, the inverse oftop()
andpop()
.