Searching for a particular element in a stack

前端 未结 4 1976
刺人心
刺人心 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条回答
  •  Happy的楠姐
    2021-01-07 02:54

    If you need to search in the stack frequently, consider using a set alongside. Always keep the set updated too: if any element is popped from stack, erase it from the set , and on any push operation onto the stack, insert into the set too.

    stack st; 
    set s;  
    
    
    //push 
    st.push(2);s.insert(2);
    
    //pop
    s.erase(st.top()); st.pop();
    
    //find (what your main objective was)
    bool ispresent = s.find(2)!=s.end() ; // on failure the iterator = s.end()
    

提交回复
热议问题