DigestCPP

Lets Understand With Example

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

std::queue c++

Queue:

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

Header File:

#include<queue>

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.
  • front(): return the first element BUT will not remove the element.
  • back(): return the last element BUT will not remove the element.
  • size(): return the size of queue/ number of element of queue.
  • empty(): return true if queue is empty otherwise false.

How to add element in queue:

Source code of std::queue with example:

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

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

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

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

    //First element
    std::cout<<qu.front()<<std::endl;

    //Last element
    std::cout<<qu.back()<<std::endl;

    //Remove element
    qu.pop();

    //First element
    std::cout<<qu.front()<<std::endl;
    std::cout<<"front cmd only return the first element BUT it will NOT remove"<<std::endl;

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

Output:

STL Queue
size:0
size:5
1
5
2
front cmd only return the first element BUT it will NOT remove
2 3 4 5 

Primary Sidebar




DigestCPP © 2023. All rights reserved.

    About Privacy Policy Terms and Conditions Contact Us Disclaimer