I have often found this weird while using Stacks in C++ and I'm not sure what the exact root of the problem is. It would be better explained with a snippet of the code: (I am trying to get the minimum value of a stack and pushing/popping etc. as usual)
class MinStack {
private:
stack<int> ans;
stack<int> min_collector;
public:
void push(int x) {
ans.push(x);
if (min_collector.empty() || getMin()>=x) {
min_collector.push(x);
}
}
void pop() {
if (ans.top()==getMin()) {
min_collector.pop();
}
ans.pop();
}
int top() {
return ans.top();
}
int getMin() {
return min_collector.top();
}
};
The above code works fine. However, in the push(int x) function, if I edit the "if" condition like this:
(getMin()>=x || min_collector.empty())
I get a runtime error, has anyone else faced this issue? Why should the order in a "or" condition matter?