I want to be able to convert a std::stack<> 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With