DigestCPP

Lets Understand With Example

  • Home
  • Design Principal
  • Design Patterns
  • C++ 11 Features
  • C++11 Multithreading
  • Contact Us

std::stack c++

Stack:

This container comes under derived or adaptor container, this follow the LIFO (last in first out). Last element will come out as first element.

Header File:

#include<stack>

Key Points:

  • It is used to store the data, we can store any number of element and remove from it.
  • Internally its implemented as deque we can change to other container.
  • push(): insert the element.
  • pop(): remove the element.
  • top(): return the top element BUT will not remove the element.
  • size(): return the size of stack/ number of element of stack.
  • empty(): return true if stack is empty otherwise false.

How to add element in stack:

Source code of std::stack with example:

/*
Program: STL Stack
Author: Alpha Master
Date: 19 September 2021
*/

//Header File
#include<iostream>
#include<stack>

int main()
{
    std::cout<<"STL Stack"<<std::endl;

   //Create empty stack object
    std::stack<int> st;
    std::cout<<"size:"<<st.size()<<std::endl;
 
    //Add element
    st.push(1);
    st.push(2);
    st.push(3);
    st.push(4);
    st.push(5);
    std::cout<<"size:"<<st.size()<<std::endl;

    //Top element
    std::cout<<st.top()<<std::endl;

    //Remove element
    st.pop();

    //Top element
    std::cout<<"Execute Top command:";
    std::cout<<st.top()<<std::endl;
    std::cout<<"Top cmd only return the top element BUT it will NOT remove"<<std::endl;

    //Display the element
    while(!st.empty())
    {
        std::cout<<st.top()<<" ";
        st.pop();
    }
    std::cout<<std::endl;
    
    return 0;
}

Output:

STL Stack
size:0
size:5
5
Execute Top command:4
Top cmd only return the top element BUT it will NOT remove
4 3 2 1 

Primary Sidebar




DigestCPP © 2023. All rights reserved.

    About Privacy Policy Terms and Conditions Contact Us Disclaimer