Queue隊列容器
Queue隊列容器是一個先進先出的線性儲存表,元素的插入只能在隊尾,元素的刪除只能在隊首。
使用Queue需要聲明標頭檔“#include <queue>”
Push():入隊,即插入元素
Pop():出隊,即刪除元素
Front():讀取隊首元素 // 優先隊列中為pop();
Back():讀取隊尾元素
Empty():判斷隊列是否為空白
Size():隊列當前元素
使用樣本:
#include <queue>
#include <iostream>
using namespace std;
int main()
{
//定義隊列
queue <int> q;
//入隊,即插入元素
q.push(1);
q.push(2);
q.push(3);
q.push(9);
//返回隊例元素數量
cout<<q.size()<<endl;
//判斷隊列是否為空白
cout<<q.empty()<<endl;
//讀取隊首元素
cout<<q.front()<<endl;
//讀取隊尾元素
cout<<q.back()<<endl;
//所有元素出列,即刪除所有元素
while(q.empty()!=true)
{
cout<<q.front()<<" ";
//刪除隊首元素
q.pop();
}
cout<<endl;
return 0;
}
優先隊列priority_queue
優先隊列容器與隊列一樣,只能從隊尾插入元素,從隊首刪除元素。但是它有一個特性,就是隊列中最大的元素總是位於隊首,所以出隊時,並非按照先進先出的原則進行,而是將當前隊列中最大的元素出隊。這點類似於給隊列裡的元素進行了由大互小的順序排序。元素的比較規則預設按元素值由大到小排序,可以重載“<”操作符來重新定義比較規則。
使用優先隊列時也需要聲明標頭檔“#include <queue>”
#include <iostream>
#include <queue>
using namespace std;
int main()
{
priority_queue<float> q;
// insert three elements into the priority queue
q.push(66.6);
q.push(22.2);
q.push(44.4);
// read and print two elements
cout << q.top() << ' ';
q.pop();
cout << q.top() << endl;
q.pop();
// insert three more elements
q.push(11.1);
q.push(55.5);
q.push(33.3);
// skip one element
q.pop();
// pop and print remaining elements
while (!q.empty()) {
cout << q.top() << ' ';
q.pop();
}
cout << endl;
}
如果優先隊列的元素類型是結構體,可以通過在結構體中重載“<“操作符的方法來修改優先隊列的優先性。
#include <queue>
#include <string>
#include <iostream>
using namespace std;
//定義結構體
struct info
{
string name;
float score;
bool operator < (const info &a) const
{
//按照score由小到大進行排列,如果要使用由大到小,使用“>”即可
return a.score<score;
}
};
int main()
{
priority_queue <info> pq;
info in;
in.name="Jack";
in.score=68.5;
pq.push(in);
in.name="Bomi";
in.score=18.5;
pq.push(in);
in.name="Peti";
in.score=90;
pq.push(in);
while(!pq.empty())
{
cout<<pq.top().name<<": "<<pq.top().score<<endl;
pq.pop();
}
return 0;
}