How can I construct or return the underlying deque from a stack?
I want to be able to convert a std::s开发者_运维问答tack<> to a std::deque<>. Is there a straightforward conversion?
It is possible to access the underlying container without copying the data, but it requires a certain amount of evil. The container is exposed as a protected member, called c
, which allows shenanigans such as this:
template <typename T>
class Shenanigans : private stack<T>
{
public:
explicit Shenanigans(stack<T>& victim) : victim(victim)
{
swap(victim);
}
~Shenanigans()
{
swap(victim);
}
using stack<T>::c;
private:
stack<T>& victim;
};
int main()
{
stack<int> s;
s.push(42);
{
Shenanigans<int> sh(s);
// The deque is accessible as sh.c, but the stack is temporarily empty.
cout << "Size: " << s.size() << " Data: " << sh.c.front() << "\n";
}
// The stack is restored.
cout << "Size: " << s.size() << " Data: " << s.top() << "\n";
}
Of course a far, far better solution is to choose a container that meets your needs.
You'll need to do it manually:
while (!stk.empty())
{
deq.push_back(stk.top());
stk.pop();
}
You need to pop all the elements off of the stack and into a different container.
If you need to do this, perhaps std::stack
is the wrong data structure for your use case.
I think if you need this, you would be better off using deque in the first place, instead of a stack. There is no way of getting at the underlying storage used by the stack adaptor, if that is what you are asking.
精彩评论