How to direct access to the elements of stack in C++?
An answer to this question on Stack Overflow.
Question
For some reason, I have to use a stack to achieve some function, but I need to reverse the output stack's elements. So I want to use stack<char,vector<char> to achieve direct access, but there may be some error in my suggestion. Can anyone tell me how to efficiently reverse the output stack's elements in C++ using STL stack?
Answer
In general you should not do this.
It's inappropriate to choose a container which is specifically designed to limit your access to its contents and then say that you really do want that access.
It's preferable to choose a container that's built to meet your needs. In this case using a deque seems more appropriate.
But, if you reeaaaaallllyyyy want to do something kind of stupid, this is how you'd access the members of the stack directly (note that this does not use gobs of extra memory and time to build a temporary reverse stack, as some of the other answers have suggested):
#include <stack>
#include <deque>
#include <cstdlib>
#include <iostream>
using namespace std;
template <class T, class S>
S& Container(stack<T, S>& q) {
struct HackedStack : private stack<T, S> {
static S& Container(stack<T, S>& q) {
return q.*&HackedStack::c;
}
};
return HackedStack::Container(q);
}
int main()
{
stack<int> st;
deque<int> &mems = Container(st);
cout<<"Putting numbers into the stack"<<endl;
for(int i=0;i<20;i++){
int temp=rand();
cout<<temp<<endl;
st.push(rand());
}
cout<<endl<<"Reading numbers in the stack"<<endl;
for(deque<int>::iterator i=mems.begin();i!=mems.end();i++)
cout<<*i<<endl;
cout<<endl<<"Taking numbers out of the stack"<<endl;
while(!st.empty()){
int temp=st.top();
st.pop();
cout<<temp<<endl;
}
return 0;
}
And, yes, if you change all of the deque references to vector references, this will still work fine. But deque is probably the preferable container to use with your stack.