问题
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
{
}
回答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!
回答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);
).
回答3:
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).
回答4:
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()
来源:https://stackoverflow.com/questions/8918762/searching-for-a-particular-element-in-a-stack