Searching for a particular element in a stack

前端 未结 4 1942
刺人心
刺人心 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).

提交回复
热议问题