
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Double Ended Priority Queue in C++
In this tutorial, we are going to create a double-ended priority queue using the set in c++.
Let's see the steps to create a double-ended queue.
Create a struct with a name as you wish.
Create a variable for the queue using the set.
size method that returns the size of the queue.
is_empty method that returns whether the queue is empty or not.
insert method to insert a new element into the queue.
get_start method that returns an element from the left side of the queue.
get_end method that returns the element from the right side of the queue.
delete_start method that deletes the first element from the left side.
delete_end method deletes the first element from the right side.
Example
Let's see the code.
#include <bits/stdc++.h> using namespace std; struct doubleEndedQueue { set<int> s; int size() { return s.size(); } string is_empty() { return s.size() == 0 ? "True" : "False"; } void insert(int x) { s.insert(x); } int get_start() { return *(s.begin()); } int get_end() { return *(s.rbegin()); } void delete_start() { if (s.size() == 0) { return; } s.erase(s.begin()); } void delete_end() { if (s.size() == 0) { return; } auto end = s.end(); end--; s.erase(end); } }; int main() { doubleEndedQueue d; cout << "is empty: " << d.is_empty() << endl; d.insert(1); d.insert(2); d.insert(3); d.insert(4); d.insert(5); cout << "is empty: " << d.is_empty() << endl; cout << "end: " << d.get_end() << endl; d.delete_end(); cout << "end: " << d.get_end() << endl; cout << "start: " << d.get_start() << endl; d.delete_start(); cout << "start: " << d.get_start() << endl; return 0; }
Output
If you run the above code, then you will get the following result.
is empty: True is empty: False end: 5 end: 4 start: 1 start: 2
Conclusion
If you have any queries in the tutorial, mention them in the comment section.