docp
docp

Reputation: 327

Finding element in stl stack cpp

I need to find an element in stack, so i figure out that i must pop element until i find this element or the stack is empty. In the other words, NOT poping when element is found OR stack is empty. What is wrong with my way of thinking?

while (!(stack.top()==searched || stack.empty()))
{
    tmp.push(stack.top());
    stack.pop();
}

Code return core dumped if stack doesnt countain searched element, but if stack.top()==searched always return 0, and stack.empty return 1, 1 OR 0 is still 1; !1=0 and 'while' should stop. Is thera any way to do that? I'm open for suggestions.

Upvotes: 2

Views: 495

Answers (1)

Ami Tavory
Ami Tavory

Reputation: 76336

It looks like your code is relying on short circuit evaluation. However, the way it works is that

cond_a || cond_b

first evaluates cond_a, only then cond_b in case this is needed. In this case, then, your code will only check whether the stack is empty after it checked the top, which is obviously a mistake. You should reverse the order of your two internal conditions.

Upvotes: 2

Related Questions