0

How exactly I can get the max_element of a stack ? STL stack doesn't any begin() or end() method that I can get the maximum by follow:

auto max = max_element(c.begin(), c.end());
Daniel Laügt
  • 1,097
  • 1
  • 12
  • 17
theshemul
  • 388
  • 1
  • 6
  • 15
  • The point of `std::stack` is that it's a stack. Choose different or none adapter. Maybe `std::priority_queue` is what you want. – LogicStuff Dec 26 '15 at 11:19
  • no , priority_queue won't work for me , because I need the arrangement as it is. :) – theshemul Dec 26 '15 at 11:23
  • 4
    But you also need to iterate through the container, so you can't have an adapter. Use `std::vector` then. You can still `push_back`, `pop_back` and `back`. `std::stack` simply hides everything else. – LogicStuff Dec 26 '15 at 11:25
  • See http://stackoverflow.com/questions/13428618/trying-to-access-an-index-of-an-stdstack?rq=1. You'd need to sub-class the stack. Preferably with private inheritance. – juanchopanza Dec 26 '15 at 11:37
  • @LogicStuff , exactly ! thanks , you can answer it :) – theshemul Dec 26 '15 at 14:21

1 Answers1

1

A std::stack has a restricted interface, which is the whole point of that abstraction. If not then you could just have used e.g. a 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.

  • You can use a custom derived class instead of std::stack directly.

This list is not exhaustive but they are the more natural options.

I.e. other approaches are fairly unnatural & construed.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331