Searching for a particular element in a stack

25,097

Solution 1

The C++ stack does not support random access, so there is no direct way using a stack to check if an element is contained. You can, however, make a copy of the stack and then continuously pop off that stack until the element is found.

Alternatively, if you do need to search the stack, you could consider instead using a deque, which does support random access. For example, you could use the find algorithm on a deque to search for an element:

find(myDeque.begin(), myDeque.end(), myValue);

If you need frequent searches of the stack, consider keeping a parallel set along with the stack that stores the same elements as the stack. This way, you can just use set::find to check (efficiently) whether the element exists.

Hope this helps!

Solution 2

If you need to find an element in your container, by definition stack is the wrong container for your needs. With the extremely minimal amount of information you've provided either vector or deque sound like they would provide the interface you need (std::find(c.begin(), c.end(), item);).

Share:
25,097
george mano
Author by

george mano

Updated on July 09, 2022

Comments

  • george mano
    george mano almost 2 years

    I am interested in porting this Python code to C++. As part of the port, I am using std::stack from the <stack> header. How can I determine whether some character is contained within a stack<char>? For example:

    std::stack<char> myStack
    
    if (!('y' is included in myStack)) // I know that this is wrong
    {
    }