×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

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".

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();

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();

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

// 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!

Load comments ↻





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