Does the std::stack in the C++ STL expose any iterators of the underlying container or should I use that container directly?
The std::stack does expose its underlying container (and therefore iterators) to subclasses through its protected interface. The std::stack's underlying container object corresponds to the (protected) data member c.
So if you want to access them, you could extend std::stack a little.
template>
class iterable_stack
: public std::stack
{
using std::stack::c;
public:
// expose just the iterators of the underlying container
auto begin() { return std::begin(c); }
auto end() { return std::end(c); }
auto begin() const { return std::begin(c); }
auto end() const { return std::end(c); }
};
int main()
{
iterable_stack st;
st.push(2);
st.push(5);
st.push(3);
st.push(7);
st.push(9);
for(auto i: st)
std::cout << i << ' ';
std::cout << '\n';
}
Output:
2 5 3 7 9