网站建设推广公司需要哪些岗位/人民网舆情数据中心官网
STL标准库之stack和queue
- stack的简介
- stack的使用
- queue的简介
- queue的使用
- 优先队列priority_queue
- 优先队列priority_queue的使用
stack的简介
与之前的string,vetcor,list不同的是,它们都被称为容器,而stack被称为容器适配器,容器适配器实际上是对特定类封装作为其底层的容器,stack底层的容器可以是任何标准的容器类模板或者其他的一些容器类。只要能支判空,获取尾部元素,尾插尾删,就可以称为stack。
而我们之前看到的string,vector,list均符合要求,但是默认情况下,我们使用的是双端队列作为其底层的默认容器。双端队列请移步STL标准库之deque。
stack的使用
栈的函数相对来说较少
函数名称 | 功能 |
---|---|
stack() | 构造空的栈 |
empty() | 检测stack是否为空 |
size() | 返回stack中元素的个数 |
top() | 返回栈顶元素 |
push() | 压栈 |
pop() | 出栈 |
使用方式:
stack<int> s();
s.empty();
s.top();
s.push();
s.pop();
queue的简介
队列和栈相同,都是容器适配器。只要符合先进先出的操作,就可以称为队列,其底层容器可以是标准容器类模板之一,符合:检测是否为空,返回有效元素个数,返回对头元素队尾元素,入队出队就可以。
实际上标准容器中deque和list都能够满足这些要求,但是在默认情况下,我们使用的是deque作为底层容器。双端队列请移步STL标准库之deque。
queue的使用
函数名称 | 功能 |
---|---|
queue() | 构造空队列 |
empty() | 判断是否为空 |
size() | 返回有效元素个数 |
front() | 返回队头元素 |
back() | 返回队尾元素 |
push() | 入队 |
pop() | 出队 |
优先队列priority_queue
优先队列也是一种适配器,它的第一个元素总是大于它包含的其他元素。
这个结构和堆非常相似,只要能够满足检测是否为空,返回有效元素个数,尾插尾删,即可。
优先队列priority_queue的使用
函数名称 | 功能 |
---|---|
priority_queue()/priority_queue(first, last) | 构造空的优先级队列 |
empty() | 检测优先级队列是否为空 |
top() | 返回优先级队列中最大元素(堆顶元素) |
push(x) | 在优先级队列中插入元素x |
pop() | 删除优先级队列中最大元素(堆顶元素) |
使用方式:
#include <vector>
#include <queue>
#include <functional> // greater算法的头文件
void TestPriorityQueue()
{// 默认情况下,创建的是大堆,其底层按照小于号比较vector<int> v{3,2,7,6,0,4,1,9,8,5};priority_queue<int> q1;for (auto& e : v)q1.push(e);cout << q1.top() << endl;// 如果要创建小堆,将第三个模板参数换成greater比较方式priority_queue<int, vector<int>, greater<int>> q2(v.begin(), v.end());cout << q2.top() << endl;
}
注意:若在优先级队列中存放的是自定义类型的数据,那么需要在自定义类型中提供大于号和小于号的重载
class Date
{
public:Date(int year = 1900, int month = 1, int day = 1): _year(year), _month(month), _day(day){}bool operator<(const Date& d)const{return (_year < d._year) ||(_year == d._year && _month < d._month) ||(_year == d._year && _month == d._month && _day < d._day);}bool operator>(const Date& d)const{return (_year > d._year) ||(_year == d._year && _month > d._month) ||(_year == d._year && _month == d._month && _day > d._day);}friend ostream& operator<<(ostream& _cout, const Date& d){_cout << d._year << "-" << d._month << "-" << d._day;return _cout;}
private:int _year;int _month;int _day;
};
void TestPriorityQueue()
{// 大堆,需要用户在自定义类型中提供<的重载priority_queue<Date> q1;q1.push(Date(2018, 10, 29));q1.push(Date(2018, 10, 28));q1.push(Date(2018, 10, 30));cout << q1.top() << endl;// 如果要创建小堆,需要用户提供>的重载priority_queue<Date, vector<Date>, greater<Date>> q2;q2.push(Date(2018, 10, 29));q2.push(Date(2018, 10, 28));q2.push(Date(2018, 10, 30));cout << q2.top() << endl;
}