Searching for a particular element in a stack

前端 未结 4 1977
刺人心
刺人心 2021-01-07 02:10

I am interested in porting this Python code to C++. As part of the port, I am using std::stack from the header. How can I determine w

4条回答
  •  情歌与酒
    2021-01-07 03:07

    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!

提交回复
热议问题