C++ 中的双端队列和优先级队列


众所周知,队列数据结构是先入先出数据结构。队列还有一些变体。它们是双端队列和优先级队列。

双端队列基本上是双端队列。因此,有两个 front(前)和 two rear(后)对。一对 front(前)和 rear(后)指针用于从左侧描述队列,而另一对用于从右侧描述队列。在此结构中,我们可以从两侧插入或删除元素。这里我们将看到一些使用双端队列 STL 的 C++ 代码以了解其功能。

示例(双端队列)

 实时演示

#include <iostream>
#include <deque>
using namespace std;
void dequeElements(deque <int> que) {
   deque <int> :: iterator it;
   for (it = que.begin(); it != que.end(); ++it)
      cout << *it << " ";
   cout <<endl;
}
int main() {
   deque <int> que;
   que.push_back(10);
   que.push_front(20);
   que.push_back(30);
   que.push_front(15);
   cout << "Currently que is holding : ";
   dequeElements(que);
   cout <<"Size of dequeue : " <<que.size() << endl;
   cout << "Element at position 2 : " << que.at(2) << endl;
   cout << "Element at front position : " << que.front() << endl;
   cout << "Element at back position : " << que.back() << endl;
   cout << "Delete from front side : ";
   que.pop_front();
   dequeElements(que);
   cout << "Delete from back side : ";
   que.pop_back();
   dequeElements(que);
}

输出

Currently que is holding : 15 20 10 30
Size of dequeue : 4
Element at position 2 : 10
Element at front position : 15
Element at back position : 30
Delete from front side : 20 10 30
Delete from back side : 20 10

队列的另一个变体是优先级队列。在此结构中,队列中的每个元素都有自己的优先级。将项目插入队列时,我们必须为此分配优先级值。它将首先删除优先级最高的元素。实现优先级队列最简单的方法之一是使用堆数据结构。

让我们看一个 C++ 代码用于优先级的队列 STL。此处优先级根据值来分配。因此更高的值将被视为最高优先级的元素。

示例(优先级队列)

 实时演示

#include <iostream>
#include <queue>
using namespace std;
void dequeElements(priority_queue <int> que) {
   priority_queue <int> q = que;
   while(!q.empty()){
      cout << q.top() << " ";
      q.pop();
   }
   cout << endl;
}
int main() {
   priority_queue <int> que;
   que.push(10);
   que.push(20);
   que.push(30);
   que.push(5);
   que.push(1);
   cout << "Currently que is holding : ";
   dequeElements(que);
   cout << "Size of queue : " <<que.size() << endl;
   cout << "Element at top position : " << que.top() << endl;
   cout << "Delete from queue : ";
   que.pop();
   dequeElements(que);
   cout << "Delete from queue : ";
   que.pop();
   dequeElements(que);
}

输出

Currently que is holding : 30 20 10 5 1
Size of queue : 5
Element at top position : 30
Delete from queue : 20 10 5 1
Delete from queue : 10 5 1

更新于: 10-Aug-2020

2K+ 浏览

启动你的事业

完成该课程获得认证

开始
广告
© . All rights reserved.