std::stack
provides a strictly last-in-first-out view of the underlying container, and that's the point of it: to restrict the use of the underlying container to LIFO.
And so it does not provide iteration.
However, it does provide the underlying container as a protected
member, which means that it's designed for being derived from. In your derived class you can provide iterators, and whatever you want. Also it's possible to just access that protected
member of an ordinary std::stack
, even without using any cast (namely via implicit conversion of member data pointer).
Re the added 2nd question,
” why doesn't it make sense to have iterators for stack?
It can make sense, but in most cases it would provide the non-LIFO access that std::stack
is designed to remove, i.e. in most cases it would be at odds with the very purpose of std::stack
.
For debugging, one's debugger will show the contents of a std::stack
, so there's no big need to have direct support for doing it in code.
Example:
#include <iostream>
#include <stack>
namespace cppx {
using std::stack;
namespace hack {
template< class Item >
auto container_of( stack<Item> const& st )
-> typename stack<Item>::container_type const&
{
struct Hacked: stack<Item> { using stack<Item>::c; };
return st.*&Hacked::c;
}
} // namespace hack
template< class Item >
auto begin( stack<Item> const& st )
{ return hack::container_of( st ).begin(); }
template< class Item >
auto end( stack<Item> const& st )
{ return hack::container_of( st ).end(); }
} // namespace cppx
auto main()
-> int
{
using namespace std;
stack<int> st;
for( int const x : {3, 1, 4, 1, 5, 9, 2, 6, 5, 4} )
{
st.push( x );
}
using cppx::begin; using cppx::end;
for( auto it = begin( st ); it != end( st ); ++it )
{
cout << *it << " ";
}
cout << endl;
}
Since in this example begin
and end
are not placed in namespace std
, a range based loop would not compile.
I didn't do that because the legality (validity) of specializing a standard function for a standard container, in namespace std
, is an issue I don't want to get into here. I think it's not permitted, although specializing for one's own type would be OK. But I'm not sure.