简体   繁体   English

在堆栈上使用std :: max_element <int>

[英]Using std::max_element on a stack<int>

How exactly I can get the max_element of a stack ? 我究竟如何才能获得堆栈的max_element? STL stack doesn't any begin() or end() method that I can get the maximum by follow: STL堆栈没有任何我可以通过以下方法获得最大值的begin()end()方法:

auto max = max_element(c.begin(), c.end());

A std::stack has a restricted interface, which is the whole point of that abstraction. std::stack具有受限制的接口,这是抽象的全部要点。 If not then you could just have used eg a std::deque . 如果没有,那么您可能只使用了std::deque But you have a number of options: 但是您有很多选择:

  • You can pop all items. 您可以弹出所有项目。 If you desire the original stack back at the end then you can just push them back. 如果您希望将原始堆栈放回最后,则可以将它们推回原位。

  • You can access the underlying container (without using a derived class). 您可以访问基础容器(不使用派生类)。 It's a protected member. 它是受保护的成员。 The infamous C++ type system loophole for member pointers is helpful, if you're afraid of casting and formally undefined behavior. 如果您担心强制转换和形式上未定义的行为,那么臭名昭著的C ++类型系统漏洞会有助于成员指针。

  • You can use a custom derived class instead of std::stack directly. 您可以直接使用自定义派生类而不是std::stack

This list is not exhaustive but they are the more natural options. 此列表并不详尽,但是它们是更自然的选择。

Ie other approaches are fairly unnatural & construed. 即,其他方法是相当不自然的和可理解的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM