在堆栈中搜索特定元素

新手上路,请多包涵

我有兴趣 将此 Python 代码 移植到 C++。作为端口的一部分,我正在使用来自 std::stack <stack> 标头的 —。如何确定某个字符是否包含在 stack<char> 中?例如:

 std::stack<char> myStack

if (!('y' is included in myStack)) // I know that this is wrong
{
}

原文由 george mano 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 916
1 个回答

C++ stack 不支持随机访问,因此无法直接使用 stack 检查是否包含元素。但是,您可以制作堆栈的副本,然后连续 pop 离开该堆栈,直到找到该元素。

或者,如果您确实需要搜索 stack ,您可以考虑改用 deque ,它确实支持随机访问。例如,您可以在 --- 上使用 deque find 算法来搜索元素:

 std::find(myDeque.begin(), myDeque.end(), myValue);

If you need to frequently search of the stack , consider keeping a parallel std::set along with the stack that stores the same elements as the stack 。这样,您可以只使用 set::find 来(有效地)检查元素是否存在。

希望这可以帮助!

原文由 templatetypedef 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏