C++ STL Container Fundamentals: Stack

Last updated by Swaminathan Iyer on Sep 25, 2024 at 10:58 PM
| Reading Time: 3 minutes

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 < int > stackExample) {
    stack < int > 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 < int > 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 < int > 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
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:

Strange Tier-1 Neural “Power Patterns” Used By 20,013 FAANG Engineers To Ace Big Tech Interviews

100% Free — No credit card needed.

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:

IK courses Recommended

Master ML interviews with DSA, ML System Design, Supervised/Unsupervised Learning, DL, and FAANG-level interview prep.

Fast filling course!

Get strategies to ace TPM interviews with training in program planning, execution, reporting, and behavioral frameworks.

Course covering SQL, ETL pipelines, data modeling, scalable systems, and FAANG interview prep to land top DE roles.

Course covering Embedded C, microcontrollers, system design, and debugging to crack FAANG-level Embedded SWE interviews.

Nail FAANG+ Engineering Management interviews with focused training for leadership, Scalable System Design, and coding.

End-to-end prep program to master FAANG-level SQL, statistics, ML, A/B testing, DL, and FAANG-level DS interviews.

Select a course based on your goals

Learn to build AI agents to automate your repetitive workflows

Upskill yourself with AI and Machine learning skills

Prepare for the toughest interviews with FAANG+ mentorship

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:

Almost there...
Share your details for a personalised FAANG career consultation!
Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!

Registration completed!

🗓️ Friday, 18th April, 6 PM

Your Webinar slot

Mornings, 8-10 AM

Our Program Advisor will call you at this time

Register for our webinar

Transform Your Tech Career with AI Excellence

Transform Your Tech Career with AI Excellence

Join 25,000+ tech professionals who’ve accelerated their careers with cutting-edge AI skills

25,000+ Professionals Trained

₹23 LPA Average Hike 60% Average Hike

600+ MAANG+ Instructors

Webinar Slot Blocked

Interview Kickstart Logo

Register for our webinar

Transform your tech career

Transform your tech career

Learn about hiring processes, interview strategies. Find the best course for you.

Loading_icon
Loading...
*Invalid Phone Number

Used to send reminder for webinar

By sharing your contact details, you agree to our privacy policy.
Choose a slot

Time Zone: Asia/Kolkata

Choose a slot

Time Zone: Asia/Kolkata

Build AI/ML Skills & Interview Readiness to Become a Top 1% Tech Pro

Hands-on AI/ML learning + interview prep to help you win

Switch to ML: Become an ML-powered Tech Pro

Explore your personalized path to AI/ML/Gen AI success

Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!
Registration completed!
🗓️ Friday, 18th April, 6 PM
Your Webinar slot
Mornings, 8-10 AM
Our Program Advisor will call you at this time

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

Your PDF Is One Step Away!

The 11 Neural “Power Patterns” For Solving Any FAANG Interview Problem 12.5X Faster Than 99.8% OF Applicants

The 2 “Magic Questions” That Reveal Whether You’re Good Enough To Receive A Lucrative Big Tech Offer

The “Instant Income Multiplier” That 2-3X’s Your Current Tech Salary

Transform Your Tech Career with AI Excellence

Join 25,000+ tech professionals who’ve accelerated their careers with cutting-edge AI skills

Join 25,000+ tech professionals who’ve accelerated their careers with cutting-edge AI skills

Webinar Slot Blocked

Loading_icon
Loading...
*Invalid Phone Number
By sharing your contact details, you agree to our privacy policy.
Choose a slot

Time Zone: Asia/Kolkata

Build AI/ML Skills & Interview Readiness to Become a Top 1% Tech Pro

Hands-on AI/ML learning + interview prep to help you win

Choose a slot

Time Zone: Asia/Kolkata

Build AI/ML Skills & Interview Readiness to Become a Top 1% Tech Pro

Hands-on AI/ML learning + interview prep to help you win

Switch to ML: Become an ML-powered Tech Pro

Explore your personalized path to AI/ML/Gen AI success

Registration completed!

See you there!

Webinar on Friday, 18th April | 6 PM
Webinar details have been sent to your email
Mornings, 8-10 AM
Our Program Advisor will call you at this time