Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I construct or return the underlying deque from a stack?

Tags:

c++

I want to be able to convert a std::stack<> to a std::deque<>. Is there a straightforward conversion?

like image 440
BeeBand Avatar asked Jun 13 '10 18:06

BeeBand


1 Answers

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.

like image 88
Mike Seymour Avatar answered Oct 06 '22 03:10

Mike Seymour