C ++中的出队和优先级队列
众所周知,队列数据结构是先进先出数据结构。队列也有一些变化。这些是出队和优先级队列。
出队基本上是双端队列。因此,有两个前对和两个后对。一对前后指针用于从左侧描述队列,另一对用于从右侧描述队列。我们可以从此结构的两侧插入或删除元素。在这里,我们将看到一些使用出队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 30Size 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
队列的另一个变体是优先级队列。在这种结构中,队列中的每个元素都有其自己的优先级。当我们将项目插入队列时,我们必须为其分配优先级值。它将首先删除优先级最高的元素。要实现优先级队列,最简单的方法之一是使用堆数据结构。
让我们看一下优先队列STL的一个C ++代码。在此,根据值分配优先级。因此,较高的值将被视为最高优先级元素。
示例(优先级队列)
#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 1Size of queue : 5
Element at top position : 30
Delete from queue : 20 10 5 1
Delete from queue : 10 5 1
以上是 C ++中的出队和优先级队列 的全部内容, 来源链接: utcz.com/z/348758.html