queue::push() and queue::pop() in C++ STL

C++ STL | queue::push() and queue::pop() functions: Here, we are going to learn about push() and pop() functions of queue with the Example.
Submitted by IncludeHelp, on November 26, 2018

In C++ STL, Queue is a type of container that follows FIFO (First-in-First-Out) elements arrangement i.e. the elements which insert first will be removed first. In queue, elements are inserted at one end known as "back" and are deleted from another end known as "front".

Note: In the Data Structure, "push" is an operation to insert an element in any container, "pop" is an operation to remove an element from the container.

1) C++ STL queue::push()function

push() inserts an element to queue at the back. After executing this function, element inserted in the queue and its size increased by 1.

Syntax:

    queue_name.push(element);

2) C++ STL queue::pop() function

pop() removes an element from the front of the queue. After executing this function, the oldest element removed from the queue and its size decreased by 1.

Syntax:

    queue_name.pop();

Program:

// cpp program for queue implementation 
// Example of push() and pop()
#include <iostream>
#include <queue>
using namespace std;

//function to print the queue 
void printQueue(queue<int> q)
{
	// printing content of queue
	while (!q.empty()) {
		cout<<" "<<q.front();
		q.pop();
	}
	cout<<endl;
}

//Main finction
int main()
{
	// declaring an empty queue
	queue<int> Q;
	
	//inserting elements 
	Q.push(10);
	Q.push(20);
	Q.push(30);
	Q.push(40);
	Q.push(50);
	cout<<"Queue elements after inserting elements:"<<endl;
	printQueue(Q);
	
	//removing elements
	Q.pop();
	Q.pop();
	cout<<"Queue elements after removing elements:"<<endl;
	printQueue(Q);
	
	return 0;
}

Output

Queue elements after inserting elements: 
 10 20 30 40 50
Queue elements after removing elements:
 30 40 50
 




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.