I am not sure, if you selected the correct approach.
Because, you can use a std::deque
in the first place. It offers all functionality that a stack offers. And more.
So maybe better use a std::deque
or a std::vector
.
Additionally, deriving from standard containers is not the best idea. You may read about that here on SO.
But if you want to do that for exceptional purposes, then simply take the address of the top()
. This will be the last element in the underlying container. And if you subtract the size()
of the stack (corrected by 1), then you have a pointer to the beginning of the underlying container.
And then you can use the artificial iterator and subscript operator []
as expected.
Please see the following example:
#include <vector>
#include <stack>
#include <iostream>
#include <algorithm>
#include <iterator>
using Number = int;
using UnderlyingContainer = std::vector<Number>;
using Stack = std::stack< Number, UnderlyingContainer>;
using StackIterator = Number *const;
int main()
{
// Put the test data onto the stack
Stack myStack{ UnderlyingContainer {1,2,3,4,5} };
if (not myStack.empty()) {
// Get "iterators"
StackIterator end = &myStack.top() + 1;
StackIterator begin = end - myStack.size();
Number *const & stk = begin;
for (size_t i{}; i < myStack.size(); ++i)
stk[i] = stk[i] + 10;
for (size_t i{}; i < myStack.size(); ++i)
std::cout << stk[i] << '\n';
std::transform(begin, end, begin, [](const Number n) {return n - 10; });
std::copy(begin, end, std::ostream_iterator<Number>(std::cout, "\n"));
}
}
So, it looks like we found what you want to have, but in reality, we simply work on the underlying container.