Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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() << "
";
    }

    // The stack is restored.
    cout << "Size: " << s.size() << " Data: " << s.top() << "
";
}

Of course a far, far better solution is to choose a container that meets your needs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...