Home
Aptitude
Categories


Home » C++ STL

queue::front() and queue::back() in C++ STL



C++ STL | queue::front() and queue::back() functions: Here, we are going to learn about front() and back() 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".

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

The function front() returns the reference to the first element in the queue i.e. the oldest element in the queue, so it is used to get the first element from the front of the list of a queue.

Syntax:

    queue_name.front();

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

The function back() returns the reference to the last element in the queue i.e. the newest element in the queue, so it is used to get the first element from the back of the list of a queue.

Syntax:

    queue_name.back();

Program:

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

//Main function
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<<"First element of the queue: "<<Q.front()<<endl;
	cout<<"Last element of the queue : "<<Q.back()<<endl;

	//removing two elements 
	Q.pop();
	Q.pop();

	cout<<"After removing two elements..."<<endl;
	cout<<"First element of the queue: "<<Q.front()<<endl;
	cout<<"Last element of the queue : "<<Q.back()<<endl;

	return 0;
}

Output

First element of the queue: 10 
Last element of the queue : 50 
After removing two elements... 
First element of the queue: 30 
Last element of the queue : 50 





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.