C++ STL Container Fundamentals: Stack

Last updated by Swaminathan Iyer on Sep 25, 2024 at 10:58 PM
Contents

The Standard Template Library (STL) in C++ is a powerful software library that’s a set of C++ template classes. It provides built-in algorithms, functions, iterators, and containers. This article focuses on the C++ STL container stack.

STL containers are objects that can store multiple elements, manage any storage required for the elements, and offer member functions we can use to access them. A container may allow elements of either the same type or different types to be stored in it. Depending on this, and on whether it is unordered, the containers are divided into three types:

  • Sequence Containers: deque, arrays, vector, list, and forward_list
  • Associative Containers: set, multiset, map, and multimap
  • Unordered Associative Containers: unordered_set, unordered_multiset, unordered_map, and unordered_multimap

There are also Container Adapters: queue, priority_queue, and stack that are a subset of containers. These container adapters offer a different interface for sequential containers. 

To help you harness the power of STL and be a more efficient developer, we’re doing a series on C++ STL container fundamentals. This article focuses on the C++ STL container stack (check out the learn page for more). 

Having trained over 10,000 software engineers, we know what it takes to crack the toughest tech interviews. Our alums consistently land offers from FAANG+ companies. The highest ever offer received by an IK alum is a whopping $1.267 Million!

At IK, you get the unique opportunity to learn from expert instructors who are hiring managers and tech leads at Google, Facebook, Apple, and other top Silicon Valley tech companies.

Want to nail your next tech interview? Sign up for our FREE Webinar.

In this article, we’ll cover:

  • C++ STL Container Fundamentals: Stack
  • Use of the C++ STL Container Stack
  • Methods of Stack
  • How to Use the C++ STL Container Stack
  • FAQs on C++ STL Container Fundamentals: Stack

C++ STL Container Fundamentals: Stack

In C++ STL, stack is a container adapter that works with the LIFO (last in first out) arrangement —  we add elements at the top and delete them from the top. An encapsulated object of vector or deque or list serves as a stack’s underlying container. Like other containers, stack provides a specific set of member functions to access its elements.

Use of the C++ STL Container Stack

Stacks are used widely for problems involving:

  • Expression evaluation
  • Browsers
  • Books, clothes, bangles, plates, etc.
  • Phone
  • Text editor
  • Parenthesis matching in expressions
  • Memory management
  • The temporary storage of information

Methods of Stack

Here are the several methods associated with stack in STL:

  • stack::empty()
  • stack::size() 
  • stack::top()
  • stack::swap(stack2)
  • stack::push(element) 
  • stack::pop() 

Let us now see what some of the most commonly used stack methods do and how to use them in the next section via an example.

How to Use the C++ STL Container stack

Here, we take a look at how you can use a stack as a C++ STL container for a smoother coding experience:

Code


// Stack in STL
#include 
#include 

using namespace std;

// Print the stack
void printStack(stack  stackExample) {
    stack  stackToPrint = stackExample;

    // Printing the stack by printing the top element then
    // removing it from the stack till the stack is empty

    while (!stackToPrint.empty()) {
        cout << stackToPrint.top() << " ";
        stackToPrint.pop();
    }
    cout << "n";
}

int main() {
    stack  stackExample;
    // Pushing elements into stack
    stackExample.push(9);
    stackExample.push(8);
    stackExample.push(7);
    stackExample.push(6);
    stackExample.push(5);
    stackExample.push(4);
    stackExample.push(3);
    stackExample.push(2);
    stackExample.push(1);
    stackExample.push(0);

    // Printing the stack
    cout << "Contents of stackExample are: ";
    printStack(stackExample);

    // Popping the topmost element of the stack twice OR Popping the two topmost elements of the stack
    stackExample.pop();
    stackExample.pop();

    // Printing the stack after popping the top two elements
    cout << "Contents of stackExample after popping the top two elements: ";
    printStack(stackExample);

    // Printing the size of the stack
    cout << "The size of stackExample is: " << stackExample.size() << endl;

    // Printing the element at the top of the stack
    cout << "The element at the top of stackExample is: " << stackExample.top() << endl;

    stack  stackExample2;

    // Checking if the two stacks are empty
    cout << "Is stackExample empty?: " << stackExample.empty() << endl;
    cout << "Is stackExample2 empty?: " << stackExample2.empty() << endl;

    // Swapping stackExample and stackExample2
    stackExample.swap(stackExample2);

    // Checking if the stackExample is empty after the swap with stackExample2
    cout << "Is stackExample empty after the swap with stackExample2?: " << stackExample.empty();

}

Output


Contents of stackExample are: 0 1 2 3 4 5 6 7 8 9 
Contents of stackExample after popping the top two elements: 2 3 4 5 6 7 8 9 
The size of stackExample is: 8
The element at the top of stackExample is: 2
Is stackExample empty?: 0
Is stackExample2 empty?: 1
Is stackExample empty after the swap with stackExample2?: 1

Check out the learn page for more.

FAQs on C++ STL Container Fundamentals: stack

Q1. What is a stack in C++ STL?

Stack in C++ STL is a LIFO (last-in-first-out) container adapter that uses an encapsulated vector/deque/list object as its underlying container. In a stack, we both add and delete elements only from the top of the stack.

Q2. What are stacks in C++ used for?

Stacks are used widely in expression evaluation and parentheses matching, browsers, text editors: undo/redo, memory management, phones, books, clothes, bangles, plates, and temporary storage of information.

Q3. What functions are associated with stack in C++ STL?

Empty, size, top, pop, and push are some functions associated with a stack in C++ STL.

Q4. What type of data structure container is a stack in C++ STL?

Stack in C++ STL provides a LIFO or Last In First Out type of container data structure,

Q5. What is an overflow and underflow condition in a stack?

An overflow condition occurs when you’re trying to push an element, but the stack is full. An underflow condition occurs when you’re trying to pop an element, but the stack is empty. 

Ready to Nail Your Next Coding Interview?

Whether you’re a coding engineer gunning for a software developer or software engineer role, a tech lead, or you’re targeting management positions at top companies, IK offers courses specifically designed for your needs to help you with your technical interview preparation!

If you’re looking for guidance and help with getting started, sign up for our FREE webinar. As pioneers in the field of technical interview preparation, we have trained thousands of software engineers to crack the most challenging coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!

Sign up now!

‍

Last updated on: September 25, 2024
Author
Swaminathan Iyer
Product @ Interview Kickstart | Ex Media.net | Business Management - XLRI Jamshedpur. Loves building things and burning pizzas!
Register for our webinar

Uplevel your career with AI/ML/GenAI

Loading_icon
Loading...
1 Enter details
2 Select webinar slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Spring vs Spring Boot

Spring vs Spring Boot: Simplifying Java Application Development

Reinforcement Learning: Teaching Machines to Make Optimal Decisions

Reinforcement Learning: Teaching Machines to Make Optimal Decisions

Product Marketing vs Product Management

Product Marketing vs Product Management

Java Scanner reset()

The upper() Function in Python

Insertion Sort Algorithm

Ready to Enroll?

Get your enrollment process started by registering for a Pre-enrollment Webinar with one of our Founders.

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC

Register for our webinar

How to Nail your next Technical Interview

Loading_icon
Loading...
1 Enter details
2 Select slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Get tech interview-ready to navigate a tough job market

Best suitable for: Software Professionals with 5+ years of exprerience
Register for our FREE Webinar

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC