在堆栈中搜索特定元素 [英] Searching for a particular element in a stack
问题描述
我有兴趣移植这个Python代码到C ++。作为端口的一部分,我使用< stack>
头中的 std :: stack
如何确定某个字符是否包含在 stack< char>
中?例如:
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
{
}
推荐答案
C ++ stack
不支持随机存取,因此没有直接的方法使用 stack
来检查是否包含元素。然而,您可以创建一个堆栈的副本,然后连续 pop
关闭该堆栈,直到找到该元素。
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.
或者,如果你确实需要搜索 stack
,你可以考虑使用 deque
随机访问。例如,您可以在 deque
上使用 find
算法搜索元素:
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);
如果您需要频繁搜索 stack
,考虑保留一个并行 set
以及存储与堆栈相同的元素的
。这样,你可以使用 stack
set :: find
来检查(有效地)元素是否存在。
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.
这有助于!
这篇关于在堆栈中搜索特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!