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);
int firstElement = myQueue.front();
cout << firstElement << endl;
return 0;
}
|
Java
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 );
int firstElement = myQueue.peek();
System.out.println(firstElement);
}
}
|
C#
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);
int firstElement = myQueue.Peek();
Console.WriteLine(firstElement);
}
}
|
Python3
from queue import Queue
myQueue = Queue()
myQueue.put( 1 )
myQueue.put( 2 )
myQueue.put( 3 )
firstElement = myQueue.queue[ 0 ]
print (firstElement)
|
Javascript
let myQueue = [];
myQueue.push(1);
myQueue.push(2);
myQueue.push(3);
let firstElement = myQueue[0];
console.log(firstElement);
|
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);
}
}
|
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);
}
}
|
Python3
from queue import Queue
myQueue = Queue()
myQueue.put( 1 )
myQueue.put( 2 )
myQueue.put( 3 )
myQueue.get()
newFirstElement = myQueue.queue[ 0 ]
print (newFirstElement)
|
Javascript
const myQueue = [];
myQueue.push(1);
myQueue.push(2);
myQueue.push(3);
myQueue.shift();
const newFirstElement = myQueue[0];
console.log(newFirstElement);
|
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);
}
}
|
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];
}
}
|
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)
|
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;
}
}
const myPriorityQueue = new PriorityQueue((a, b) => b - a);
myPriorityQueue.push(3);
myPriorityQueue.push(1);
myPriorityQueue.push(2);
const highestPriorityElement = myPriorityQueue.top();
console.log(highestPriorityElement);
|
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);
}
}
|
Python3
import queue
myQueue = queue.PriorityQueue()
myQueue.put( 3 )
myQueue.put( 1 )
myQueue.put( 2 )
myQueue.get()
newHighestPriorityElement = myQueue.queue[ 0 ]
print (newHighestPriorityElement)
|
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; }
}
}
|
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);
|
Time Complexity: O(logN), Where N is the number of elements to be pushed or poped.
Auxiliary Space: O(1)
Similar Reads
Why can't a Priority Queue wrap around like an ordinary Queue?
Priority Queue: A priority queue is a special type of queue in which each element is assigned a priority value. And elements are served based on their priority. This means that elements with higher priority are served first. However, if elements with the same priority occur, they will be served in t
3 min read
Turn a Queue into a Priority Queue
What is Queue?Queue is an abstract data type that is open at both ends. One end is always used to insert data (enqueue) which is basically the rear/back/tail end and the other which is the front end is used to remove data (dequeue). Queue follows First-In-First-Out (FIFO) methodology, i.e., "the dat
9 min read
What is Priority Queue | Introduction to Priority Queue
A priority queue is a type of queue that arranges elements based on their priority values. Each element has a priority associated. When we add an item, it is inserted in a position based on its priority.Elements with higher priority are typically retrieved or removed before elements with lower prior
6 min read
Why is Binary Heap Preferred over BST for Priority Queue?
A typical Priority Queue requires following operations to be efficient. Get Top Priority Element (Get minimum or maximum)Insert an elementRemove top priority elementDecrease KeyA Binary Heap supports above operations with following time complexities: O(1)O(Logn)O(Logn)O(Logn) A Self Balancing Binary
2 min read
Efficient way to initialize a priority queue
STL Priority Queue is the implementation of Heap Data Structure. By default, it's a max heap, and can be easily for primitive data types. There are some important applications of it which can be found in this article. Priority queue can be initialized in two ways either by pushing all elements one b
7 min read
Can we use Simple Queue instead of Priority queue to implement Dijkstra's Algorithm?
What is Dijkstra's Algorithm? Dijkstra's Algorithm is used for finding the shortest path between any two vertices of a graph. It uses a priority queue for finding the shortest path. For more detail, about Dijkstra's Algorithm, you can refer to this article. Why Dijkstra's Algorithm uses a Priority Q
2 min read
priority_queue::swap() in C++ STL
Priority queues are a type of container adaptors, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue. However, in C++ STL (by default) the largest element is at the top. We can also create a priority queue having the sma
3 min read
Should we declare as Queue or Priority Queue while using Priority Queue in Java?
Queue: Queue is an Interface that extends the collection Interface in Java and this interface belongs to java.util package. A queue is a type of data structure that follows the FIFO (first-in-first-out ) order. The queue contains ordered elements where insertion and deletion of elements are done at
3 min read
Why Doesn't std::queue::pop Return Value?
In C++, we use std::queue which is a container adapter in the standard template library (STL) and is used for managing a collection of elements in a FIFO (first-in, first-out) order. One common question that arises in our mind is why the pop function in std::queue does not return the value it remove
3 min read
Difference Between heapq and PriorityQueue in Python
In this article, we are going to see the difference between heapq and PriorityQueue in Python. Differences between PriorityQueue and heapqPython queue PriorityQueue is thread-safe, but heapq doesn't guarantee thread safety.PriorityQueue implements locking to ensure thread safety, thus it is slower t
3 min read