栈、队列和优先队列
栈 ( 后进先出 )
STL的 stack 头文件提供了栈,用 stack< int > s 方式定义。
- push(x) 入栈 x 元素
- pop() 出栈
- empty() 堆栈为空则返回真
- size() 返回栈中元素数目
- top() 返回栈顶元素
#include<iostream>
#include<string>
#include<stack>
using namespace std;
int main(){
stack<string> s;
s.push("A");
s.push("B");
s.push("C");
s.push("D");
s.pop(); // D 出栈
cout<<s.top()<<endl; //输出栈顶 C
cout<<s.size()<<endl; //栈中元素的数目 3
cout<<s.empty()<<endl; // 栈不为空,输出0
return 0;
}
队列
STL队列定义在头文件 < queue > 中,用 " queue< int > s " 声明一个队列。
- push(x) 在队尾压入新元素
- pop() 删除队列首元素但不返回其值
- empty() 如果队列为空返回true,否则返回false
- size() 返回队列中元素的个数
- front() 返回队首元素的值,但不删除该元素
- back() 返回队尾元素的值,但不删除该元素
#include<iostream>
#include<queue>
#include<string>
using namespace std;
int main()
{
queue<string> s;
s.push("A");
s.push("B");
s.push("C");
s.push("D");
s.pop(); //删除队首元素 A
cout << s.front() << endl; //队首元素 B
cout << s.back() << endl; //队尾元素 D
cout << s.size() << endl; //队中元素的个数 3
cout << s.empty() << endl;
return 0;
}
优先队列
STL的queue头文件提供了优先队列,用 “priority_queue < int > s” 方式定义。
这个s默认是less降序排序是一个“越小的整数优先级越低的优先队列”。由于出队元素并不是最先进队的元素,出队的方法由 front() 变为top()
- 升序队列
priority_queue <int,vector<int>,greater<int> > s
- 降序队列
priority_queue <int,vector<int>,less<int> > s
#include<iostream>
#include<functional>
#include<queue>
using namespace std;
int main()
{
//priority_queue<int>pq; 与less一样 10401
priority_queue<int, vector<int>, greater<int> > pq;
pq.push(10001);
pq.push(1000);
pq.push(10401);
pq.push(1002);
cout << pq.top() << endl; //1000
}