Searching for a particular element in a stack

前端 未结 4 1969
刺人心
刺人心 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 02:54

    Since you wish to implement DFS and BFS, using std::stack (for DFS) and std::queue (for BFS) is indeed appropriate to keep not yet visited nodes, and you only need to use push() and pop() methods of these containers.

    But stack and queue are not sufficient to keep visited nodes. My preference would be to use an associative container, e.g. std::set, better yet unordered_set if your C++ compiler has it, because searching an arbitrary value in an associative container is faster than in a sequence like vector or deque (unless data are sorted there).

    0 讨论(0)
  • 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<int> st; 
    set<int> 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()
    
    0 讨论(0)
  • 2021-01-07 03:06

    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);).

    0 讨论(0)
  • 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!

    0 讨论(0)
提交回复
热议问题