Search code examples
c++stdstack

Is std::stack contiguous?


I wanted to find the maximum element in a stack, and thought of using std::max_element.

Then I came to know that std::stack does not have begin() and end() functions. After surfing the net, I saw a hack:

stack<int> s({0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
auto end = &s.top() + 1;     // instead of std::end
auto begin = end - s.size(); // instead of std::begin
cout << "Max = " << *max_element(begin, end);

It does seem to work, you can see it online.

But when I submitted my code, it failed some of the test cases. Is std::stack really contiguous?


Solution

  • Is std::stack contiguous? I would say, it doesn't matter. std::stack is not a container, but an adapter, and its idea is the stack abstraction and a deliberate restriction of interfaces.

    Even if it were contiguous, accessing elements of std::stack by any means but .top() would be a violation of its semantics. If you need such an access, you should not use std::stack in the first place. Don't confuse the reader of your code.