c++stlcontainersstdstack

std::stack implementation on different containers what is the actual difference?


when implementing an std::stack

there are a few options, for example:

   // stack with default underlying deque
   std::stack< int > intDequeStack;   

   // stack with underlying vector
   std::stack< int, std::vector< int > > intVectorStack;

   // stack with underlying list
   std::stack< int, std::list< int > > intListStack;

what advantages and disadvantages do i gain from defining std::stack on different containers when all i get from it is the same operations " push, pop and top " ?

in other words: what is the difference between a stack of deque and a stack of vector and a stack of list and why would i want to choose anything other than deque?


Solution

  • The stack inherits the performance characteristics of the underlying container.


    1 There is one level of indirection to the data, but in order to remove the last element, the linked list needs another indirection to the previous node to clear out the next-pointer.

    2 Note that you will need to move the vector when constructing the container. Copying a vector does not necessarily preserve its capacity. For example, you could use this helper:

    template <typename T>
    std::stack<T, std::vector<T>> vector_stack(
        typename std::vector<T>::size_type capacity
    ) {
        std::vector<T> vec;
        vec.reserve(capacity);
    
        return std::stack<T, std::vector<T>>{std::move(vec)};
    }