Skip to the content of the web site.

std::stack

std::stack

The stack class is a container that has three member functions with strict behavior as to what those functions perform. A stack can hold zero or more items and

  • an item is "pushed" onto the stack using push(...),
  • the item that was last pushed onto the stack can be accessed using top(), and
  • when pop() is called on the stack, that item that is at the top is the one that is removed.

Member functions and operators

We will describe the various member functions for constructing and querying this container and for inserting, accessing, and removing items from this container.

Constructing a stack

The the most common constructor simply creates an empty stack:

    std::stack<T> identifier{};

Querying a stack

As with most containers, you can query if a stack is empty with bool empty() const, and the number of items in the stack std::size_t size() const:

    // Prints '0' (false) or '1' (true)
    std::cout << identifier.empty()
              << std::endl;

    // Prints a non-negative integer
    std::cout << identifier.empty()
              << std::endl;

Inserting an item into a stack

The only operation to insert an item into a std::stack<T> is void push( T const &item ) as well as variations on this:

    identifier.push( item );

Accessing an item in a stack

The only operation to access an item in the stack is T top(), which returns a reference to the last item entered into the stack; thus, the item on the top of the stack can be replaced with a new value:

    std::cout << identifier.top()
              << std::endl;
    identifier.top() = new_value;

    // This will now print out the new value...
    std::cout << identifier.top()
              << std::endl;

Removing an item from a stack

The only operation to remove an item from the stack is void pop() which removes the most recent item inserted into the stack that is still in the stack:

    identifier.pop();

Iterators

The std::queue class does not have member functions that return iterators to items within the queue.

A possible implementation

A stack could be implemented as an array as follows:

    int stack[128];
    std::size_t top_plus_1{ 0 };

Then,

  • if n is pushed onto the stack, we assign stack[top_plus_1] = n; and increment top_plus_1,
  • top() returns stack[top_plus_1 - 1], and
  • popping from the stack decrements top_plus_1.

You can see the use of the std::stack class at replit.com.