I don't understand what that list<int> does while we declare the stack stack<int, list<int> >. It does not change the from what I tried.

2 Answers

0
UnholySheep On

As described on https://en.cppreference.com/w/cpp/container/stack, the second template parameter defines the underlying Container:

Container - The type of the underlying container to use to store the elements. The container must satisfy the requirements of SequenceContainer. Additionally, it must provide the following functions with the usual semantics:

back()
push_back()
pop_back() 

The standard containers std::vector, std::deque and std::list satisfy these requirements. By default, if no container class is specified for a particular stack class instantiation, the standard container std::deque is used.

So std::stack<int, std::list<int> > defines this stack to use a std::list as underlying container, instead of the default of std::deque

6
Barry On

stack isn't a container, it's a container adapter. You tell it what type of element to store and what container to store it in.

It looks roughly like this:

template <typename T, typename Container = std::deque<T>>
class stack {
protected:
    Container c;
public:
    void push(T const& v) { c.push_back(v); }
    void pop() { c.pop_back(); }
};

As you can see, when you change from stack<int> to stack<int, list<int>>, you're just changing the underlying container storage. The interface doesn't change at all. But the performance definitely will - deque is a much better choice for a stack than list is...