Double ended priority queue in C++ Program


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.

 Live Demo

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

Updated on: 28-Jan-2021

401 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements