Why does Queue have front but Priority-queue has top in stl?
Last Updated :
06 May, 2023
Why does the queue have front but the priority queue has top in stl?
The main difference between a queue and a priority queue is that a queue follows the FIFO (First-In-First-Out) principle, while a priority queue follows a specific priority order. In other words, the elements in a queue are processed in the order they were added, whereas the elements in a priority queue are processed based on their priority.
Queue:
A queue is a data structure that follows the FIFO (First-In-First-Out) principle, which means that the first element that is added to the queue is the first element that is removed. The elements in a queue are processed in the order they were added, and new elements are added to the back of the queue.
In the STL, the queue container is implemented as an adapter on top of other container classes, such as deque or list. The queue class provides a number of member functions, including the "front" member function, which returns a reference to the first element in the queue. This is the element that will be processed next when we call the "pop" member function to remove it from the queue.
For example: let's say we have a queue of integers {1, 2, 3}. We can use the "front" member function to access the first element in the queue, which is 1:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
queue<int> myQueue;
myQueue.push(1);
myQueue.push(2);
myQueue.push(3);
// Accessing first element
int firstElement = myQueue.front();
cout << firstElement << endl;
return 0;
}
Java
// Java code implementation
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
Queue<Integer> myQueue = new LinkedList<Integer>();
myQueue.add(1);
myQueue.add(2);
myQueue.add(3);
// Accessing first element
int firstElement = myQueue.peek();
System.out.println(firstElement);
}
}
// This code is contributed by sankar.
C#
// C# code implementation
using System;
using System.Collections.Generic;
public class GFG {
public static void Main()
{
Queue<int> myQueue = new Queue<int>();
myQueue.Enqueue(1);
myQueue.Enqueue(2);
myQueue.Enqueue(3);
// Accessing first element
int firstElement = myQueue.Peek();
Console.WriteLine(firstElement);
}
}
// This code is contributed by prasad264
Python3
from queue import Queue
myQueue = Queue()
myQueue.put(1)
myQueue.put(2)
myQueue.put(3)
# Accessing first element
firstElement = myQueue.queue[0]
print(firstElement)
# This code is contributed by Akash Jha
JavaScript
let myQueue = [];
myQueue.push(1);
myQueue.push(2);
myQueue.push(3);
// Accessing first element
let firstElement = myQueue[0];
console.log(firstElement);
// This code is contributed by Akash Jha
Time Complexity: O(1)
Auxiliary Space: O(1)
If we then call the "pop" member function to remove the first element from the queue, the next element in the queue (which is 2) becomes the first element, and we can access it using the "front" member function again:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
queue<int> myQueue;
myQueue.push(1);
myQueue.push(2);
myQueue.push(3);
myQueue.pop();
int newFirstElement = myQueue.front();
cout << newFirstElement << endl;
return 0;
}
Java
import java.util.Queue;
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
Queue<Integer> myQueue = new LinkedList<Integer>();
myQueue.add(1);
myQueue.add(2);
myQueue.add(3);
myQueue.remove();
int newFirstElement = myQueue.peek();
System.out.println(newFirstElement);
}
}
// This code is contributed by Akash Jha
C#
using System;
using System.Collections.Generic;
class Program {
static void Main(string[] args)
{
Queue<int> myQueue = new Queue<int>();
myQueue.Enqueue(1);
myQueue.Enqueue(2);
myQueue.Enqueue(3);
myQueue.Dequeue();
int newFirstElement = myQueue.Peek();
Console.WriteLine(newFirstElement);
}
}
// This code is contributed by Akash Jha
Python3
from queue import Queue
myQueue = Queue()
myQueue.put(1)
myQueue.put(2)
myQueue.put(3)
myQueue.get()
newFirstElement = myQueue.queue[0]
print(newFirstElement)
# This code is contributed by Akash Jha
JavaScript
const myQueue = [];
myQueue.push(1);
myQueue.push(2);
myQueue.push(3);
myQueue.shift();
const newFirstElement = myQueue[0];
console.log(newFirstElement);
// This code is contributed by Akash Jha
Time Complexity: O(1)
Auxiliary Space: O(1)
Priority Queue
A priority queue, on the other hand, is a data structure that orders elements based on their priority. The elements in a priority queue are processed in order of their priority, with the highest-priority element processed first. New elements are added to the priority queue based on their priority order, and the highest-priority element is always at the front of the queue.
In the STL, the priority queue container is implemented as an adapter on top of a vector or a deque, and it requires a comparison function to determine the priority order of elements. The priority queue class provides a number of member functions, including the "top" member function, which returns a reference to the element with the highest priority in the queue. This is the element that will be processed next when we call the "pop" member function to remove it from the queue.
For example, let's say we have a priority queue (Max-Heap) of integers {3, 1, 2}. We can use the "top" member function to access the element with the highest priority, which is 3:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
priority_queue<int> myPriorityQueue;
myPriorityQueue.push(3);
myPriorityQueue.push(1);
myPriorityQueue.push(2);
int highestPriorityElement
= myPriorityQueue.top();
cout << highestPriorityElement << endl;
return 0;
}
Java
import java.util.*;
public class Main {
public static void main(String[] args) {
PriorityQueue<Integer> myPriorityQueue = new PriorityQueue<Integer>();
myPriorityQueue.add(3);
myPriorityQueue.add(1);
myPriorityQueue.add(2);
int highestPriorityElement = myPriorityQueue.peek();
System.out.println(highestPriorityElement);
}
}
// This code is contributed by Akash Jha
C#
using System;
using System.Collections.Generic;
class MainClass {
public static void Main (string[] args) {
PriorityQueue<int> myPriorityQueue = new PriorityQueue<int>();
myPriorityQueue.Push(3);
myPriorityQueue.Push(1);
myPriorityQueue.Push(2);
int highestPriorityElement = myPriorityQueue.Top();
Console.WriteLine(highestPriorityElement);
}
}
public class PriorityQueue<T> where T : IComparable<T> {
private List<T> data;
public PriorityQueue() {
this.data = new List<T>();
}
public void Push(T item) {
data.Add(item);
int ci = data.Count - 1;
while (ci > 0) {
int pi = (ci - 1) / 2;
if (data[ci].CompareTo(data[pi]) >= 0)
break;
T tmp = data[ci]; data[ci] = data[pi]; data[pi] = tmp;
ci = pi;
}
}
public T Top() {
if (this.data.Count == 0)
throw new InvalidOperationException("The priority queue is empty.");
return data[0];
}
}
// This code is contributed by Akash Jha
Python3
import queue
my_queue = queue.PriorityQueue()
my_queue.put(3)
my_queue.put(1)
my_queue.put(2)
highest_priority_element = my_queue.get()
print(highest_priority_element)
# This code is contributed by Akash Jha
JavaScript
class PriorityQueue {
constructor(compareFn) {
this.compareFn = compareFn || ((a, b) => a - b);
this.items = [];
}
push(item) {
this.items.push(item);
this.items.sort(this.compareFn);
}
pop() {
return this.items.shift();
}
top() {
return this.items[0];
}
size() {
return this.items.length;
}
empty() {
return this.items.length === 0;
}
}
// Example usage
const myPriorityQueue = new PriorityQueue((a, b) => b - a);
myPriorityQueue.push(3);
myPriorityQueue.push(1);
myPriorityQueue.push(2);
const highestPriorityElement = myPriorityQueue.top();
console.log(highestPriorityElement);
// This code is contributed by Akash Jha
Time Complexity: O(logN), Where N is the number of elements to be pushed.
Auxiliary Space: O(1)
If we then call the "pop" member function to remove the highest-priority element from the queue, the next element with the highest priority (which is 2) becomes the new top element, and we can access it using the "top" member function again:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
priority_queue<int> myPriorityQueue;
myPriorityQueue.push(3);
myPriorityQueue.push(1);
myPriorityQueue.push(2);
myPriorityQueue.pop();
int newHighestPriorityElement = myPriorityQueue.top();
cout << newHighestPriorityElement << endl;
return 0;
}
Java
import java.util.PriorityQueue;
public class Main {
public static void main(String[] args) {
PriorityQueue<Integer> myPriorityQueue = new PriorityQueue<Integer>();
myPriorityQueue.add(3);
myPriorityQueue.add(1);
myPriorityQueue.add(2);
myPriorityQueue.poll();
int newHighestPriorityElement = myPriorityQueue.peek();
System.out.println(newHighestPriorityElement);
}
}
// This code is contributed by Akash Jha
Python3
import queue
myQueue = queue.PriorityQueue()
myQueue.put(3)
myQueue.put(1)
myQueue.put(2)
myQueue.get()
newHighestPriorityElement = myQueue.queue[0]
print(newHighestPriorityElement)
# This code is contributed by Akash Jha
C#
using System;
using System.Collections.Generic;
class MainClass {
public static void Main (string[] args) {
var myPriorityQueue = new PriorityQueue<int>();
myPriorityQueue.Push(3);
myPriorityQueue.Push(1);
myPriorityQueue.Push(2);
myPriorityQueue.Pop();
int newHighestPriorityElement = myPriorityQueue.Top();
Console.WriteLine(newHighestPriorityElement);
}
}
class PriorityQueue<T> {
private List<T> data;
private Comparison<T> comparison;
public PriorityQueue() : this(Comparer<T>.Default) {}
public PriorityQueue(IComparer<T> comparer) : this(comparer.Compare) {}
public PriorityQueue(Comparison<T> comparison) {
this.data = new List<T>();
this.comparison = comparison;
}
public void Push(T item) {
int i = data.Count;
data.Add(item);
while (i > 0) {
int p = (i - 1) / 2;
if (comparison(data[p], item) <= 0)
break;
data[i] = data[p];
i = p;
}
data[i] = item;
}
public T Pop() {
T ret = data[0];
T last = data[data.Count - 1];
data.RemoveAt(data.Count - 1);
if (data.Count > 0) {
int i = 0;
while (i * 2 + 1 < data.Count) {
int a = i * 2 + 1, b = i * 2 + 2;
if (b < data.Count && comparison(data[b], data[a]) < 0) {
a = b;
}
if (comparison(data[a], last) >= 0) {
break;
}
data[i] = data[a];
i = a;
}
data[i] = last;
}
return ret;
}
public T Top() {
if (data.Count == 0)
throw new System.InvalidOperationException("Priority queue is empty.");
return data[0];
}
public int Count {
get { return data.Count; }
}
}
// This code is contributed by Akash Jha
JavaScript
let myPriorityQueue = [];
myPriorityQueue.push(3);
myPriorityQueue.push(1);
myPriorityQueue.push(2);
myPriorityQueue.sort((a, b) => b - a);
let highestPriorityElement = myPriorityQueue[0];
console.log(highestPriorityElement);
// This code is contributed by Akash Jha
Time Complexity: O(logN), Where N is the number of elements to be pushed or poped.
Auxiliary Space: O(1)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read