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
We will describe the various member functions for constructing and querying this container and for inserting, accessing, and removing items from this container.
The the most common constructor simply creates an empty stack:
std::stack<T> identifier{};
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;
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 );
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;
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();
The std::queue class does not have member functions that return iterators to items within the queue.
A stack could be implemented as an array as follows:
int stack[128]; std::size_t top_plus_1{ 0 };
Then,
You can see the use of the std::stack class at replit.com.