#include<queue>
常用函数
- push()
- pop()
- size()
- empty()
- front()
- back()
示例
push()
- 在队尾插入一个元素
1 #include<queue> 2 #include<string> 3 #include<iostream> 4 5 using namespace std; 6 7 int main(){ 8 queue<string> q; 9 q.push("Hello World!"); 10 q.push("China"); 11 cout << q.front() << endl; 12 }
- 输出:“Hello World!”
pop()
- 将队列中最靠前位置的元素拿掉,是无返回值的void函数
1 queue<string> q; 2 q.push("Hello World!"); 3 q.push("China"); 4 q.pop(); 5 cout << q.front() << endl;
- 输出China
size()
- 返回队列中元素的个数,返回值类型为unsigned int
1 queue<string> q; 2 cout << q.size() << endl; 3 q.push("Hello World!"); 4 q.push("China"); 5 cout << q.size() << endl;
- 输出两行,分别为0和2,即队列中的元素个数
empty()
- 判断队列是否为空,若为空则返回true
1 queue<string> q; 2 cout << q.empty() << endl; 3 q.push("Hello World!"); 4 q.push("China"); 5 cout << q.empty() << endl;
- 输出两行,分别为1和0
front()
- 返回值为队列第一个元素,即最先进入队列的元素。注意只是返回,并没有把它剔除出队列
1 queue<string> q; 2 q.push("Hello World!"); 3 q.push("China"); 4 cout << q.front() << endl; 5 q.pop(); 6 cout << q.front() << endl;
- 输出两行,分别是Hello World ! 和 China。只有使用了pop后,队列最早进入的元素才会被剔除
back()
- 返回队列最后一个元素,即最晚入队的元素
1 queue<string> q; 2 q.push("Hello World!"); 3 q.push("China"); 4 cout << q.back() << endl;
- 输出为China,因为它是最后入队的。这里back仅仅是返回最后一个元素,并没有剔除它
优先队列
priority_queue<T>
- 底层是堆
1 #include <iostream> 2 #include <queue> 3 #include <ctime> 4 using namespace std; 5 6 struct cmp{ 7 bool operator()(int a, int b){ 8 return a%10 < b%10; 9 } 10 }; 11 12 int main(){ 13 srand( time(NULL) ); 14 // 默认情况下是最大堆 15 priority_queue<int> pq; 16 for( int i = 0 ; i < 10 ; i ++ ){ 17 int num = rand()%100; 18 pq.push( num ); 19 cout << "insert " << num << " in priority queue." << endl; 20 } 21 22 while( !pq.empty() ){ 23 cout<<pq.top()<<" "; 24 pq.pop(); 25 } 26 cout<<endl<<endl; 27 28 //最小堆 29 priority_queue<int, vector<int>, greater<int> > pq2; 30 31 for( int i = 0 ; i < 10 ; i ++ ){ 32 int num = rand()%100; 33 pq2.push( num ); 34 cout << "insert " << num << " in priority queue." << endl; 35 } 36 37 while( !pq2.empty() ){ 38 cout<<pq2.top()<<" "; 39 pq2.pop(); 40 } 41 cout<<endl<<endl; 42 43 // 自定义 Comparator 44 priority_queue<int ,vector<int>, cmp> pq3; 45 46 for( int i = 0 ; i < 10 ; i ++ ){ 47 int num = rand()%100; 48 pq3.push( num ); 49 cout << "insert " << num << " in priority queue." << endl; 50 } 51 52 while( !pq3.empty() ){ 53 cout<<pq3.top()<<" "; 54 pq3.pop(); 55 } 56 cout<<endl<<endl; 57 return 0; 58 }
参考
队列<queue>中的常用函数
https://www.cnblogs.com/xuning/p/3321733.html
优先队列(priority_queue)四种自定义排序方法