STL-Stack in C++ Programming


Stacks are a type of container adaptors with LIFO(Last In First Out) type of working. The element that is pushed at the end is popped out first. Push an element into the stack. Removes the element by following the LIFO order. Returns the element present at the top of the stack. Returns whether the stack is empty or not.

The program demonstrates the use of the STL Stack container in C++.

  • First, the program defines a function print which takes a stack of integers as input and prints out each element separated by a space. The function achieves this by repeatedly calling the top function to get the top element of the stack, printing it out, and then removing it from the stack using the pop function.
  • Next, the program creates a stack s of integers and adds four elements to it using the push member function.
  • The program then demonstrates several member functions of the stack container. empty returns true if the stack is empty, and size returns the number of elements in the stack. The print function is called twice to print out the contents of the stack before and after the pop member function is used to remove the top element.
  • Finally, the program returns 0 to indicate successful execution.

Source Code

#include<iostream>
#include<stack>
using namespace std;
//STL-Stack in C++
void print(stack<int> x)
{
    while (!x.empty()) {
    cout <<" " << x.top();
    x.pop();
    }
     cout<<endl;
}
int main()
{
    stack<int> s;
    s.push(10);
    s.push(20);
    s.push(30);
    s.push(40);
     cout<<"Empty or Not : "<<s.empty()<<endl;
     cout<<"Size: "<<s.size()<<endl;
     print(s);
      s.pop();
       print(s);
    return 0;
}
 

Output

Empty or Not : 0
Size: 4
 40 30 20 10
 30 20 10

To download raw file Click Here

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples