容器适配器
容器适配器为顺序容器提供了不同的
接口
stack栈(LIFO数据结构)queue队列(FIFO数据结构)priority_queue容器以提供优先级队列
stack
stack类是容器适配器,它给予程序员栈的功能–特别是FILO(先进后出)数据结构。该类模版表现为底层容器的包装器–只提供特定函数集合。栈从被称作栈顶的容器尾部推弹元素
元素访问
top栈顶元素
容量
empty空size
修改器
push栈顶插入元素emplacepop:删除栈顶元素swap:交换内容
#include <stack>
#include <iostream>
using namespace std;
int main(void)
{
//创建栈
stack<int> s;
//向栈顶插入元素
s.push(2);
s.push(6);
s.push(51);
//输出栈的数量
cout << s.size() << " elements on stack\n";
//访问栈顶元素
cout << "s Top element:" << s.top() << endl;
//删除栈顶元素
s.pop();
//输出栈的数量
cout << s.size() << "s elements on stack\n";
stack<int> a;
//将s内容与a进行交换
s.swap(a);
cout << a.size() << "a elements on stack\n";
//输出a的栈顶元素
cout << "a Top element:" << a.top() << endl;
return 0;
}
/*
3 elements on stack
s Top element:51
2s elements on stack
2a elements on stack
a Top element:6
*/queue
queue类是容器适配器,它给予程序员队列的功能–尤其是FIFO(先进先出)数据结构。
元素访问
front第一个元素back最后一个元素
容量
empty空size
修改器
push栈顶插入元素emplacepop:删除栈顶元素swap:交换内容
priority_queue
priority_queue是容器适配器(最大优先队列),它提供常数时间的(默认)最大元素最大查找,对数代价的插入与提取。可以通过用户提供的Compare更改顺序,例如用std::greater将导致最小元素作为top()出现,用piority_queue工作类似管理某些随机访问容器的堆,优势是堆不可能突然失效。
元素访问
top栈顶元素
容量
empty空size
修改器
push栈顶插入元素emplacepop:删除栈顶元素swap:交换内容
/*
environment:C++20
*/
#include <functional>
#include <queue>
#include <vector>
#include <iostream>
#include <string_view>
using namespace std;
template<typename T>
void print(string_view name, T const& q)
{
cout << name << ": \t";
for (auto const& n : q)
{
cout << n << ' ';
}
cout << endl;
}
template<typename Q>
void print_queue(string_view name, Q q)
{
//注意按照值传递q,这是因为无法再不清楚队列的情况下遍历priority_queue的内容
for (cout << name << ": \t"; !q.empty(); q.pop())
{
cout << q.top() << ' ';
}
cout << endl;
}
int main(void)
{
const auto data = { 1,8,5,6,3,4,0,9,7,2 };
print("data", data);
//最大优先队列
priority_queue<int> q1;
for (int n : data)
{
//向栈顶插入元素
q1.push(n);
}
print_queue("q1", q1);
//最小优先队列
//std::gerater<int>使得最大优先队列的行为变成最小优先队列的行为
priority_queue<int, vector<int>, greater<int>>
minq1(data.begin(), data.end());
print_queue("minq1", minq1);
return 0;
}
/*
data: 1 8 5 6 3 4 0 9 7 2
q1: 9 8 7 6 5 4 3 2 1 0
minq1: 0 1 2 3 4 5 6 7 8 9
*/