0、顺序容器简介
容器 | 定义 | 特点 | 注意 |
---|---|---|---|
vector | 可变大小数组 | 支持快速随机访问,在尾部之外的位置插入删除元素可能很慢 | 不支持push_front、emplace_front |
string | 与vector类似,用于存储字符串 | 随机访问快,在尾部插入/删除快 | 不支持push_front、emplace_front |
deque | 双端队列 | 支持快速随机访问,在头尾插入/删除速度很快 | |
list | 双向链表 | 只支持双向顺序访问,在任何位置插入/删除速度都很快 | |
forward_list | 单向链表 | 只支持单向顺序访问,在任何位置插入/删除速度都很快 | 迭代器不支持递减运算符(–);有自己版本的insert/emplace;不支持push_back、emplace_back |
array | 固定大小数组 | 支持快速随机访问,不能添加删除元素 |
一、定义
适配器(adaptor)是标准库中的一个通用概念,本质上,适配器是一种机制,能使某种事务的行为看起来像另外一种事物一样。
标准库定义了三个顺序容器适配器:stack——栈,queue——队列,priority_queue——优先级队列。
stack和queue是基于deque实现的,priority_queue是基于vector实现的。
stack只要求push_back、pop_back、back操作,因此可以使用除array和forward_list之外的任何容器类型来构造stack。
所有容器都支持的操作和类型:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GcBrGdEu-1688091990731)(C:\Users\w22200402\AppData\Roaming\Typora\typora-user-images\image-20230629161616766.png)]
二、Stack
后进先出
stack只要求push_back、pop_back、back,因此可以使用array和forward_list之外的任何容器类型来构造stack。
s.push(); //push(x)将x入栈,时间复杂度为O(1)
s.top(); //top()获得栈顶元素,O(1)
s.pop(); //pop()用以弹出栈顶元素,O(1)
s.size(); //size()返回stack内元素的个数,时间复杂度为O(1)。
s.empty(); //empty()可以检测stack是否为空,返回true为空,返回false为非空,时间复杂度为O(1)
注:在使用**pop()和top()函数之前必须先使用empty()**函数判断栈是否为空。
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<int> sta_data;
if (sta_data.empty())
{
cout << "The sta_data is empty." << endl;
}
for (int i = 0; i < 5; i++)
{
sta_data.push(i);
}
while (!sta_data.empty())
{
cout << sta_data.top() << ' ';
sta_data.pop();
}
cout << endl;
system("pause");
return 0;
}
stack用来模拟实现一些递归,防止程序对栈内存的限制而导致程序运行出错。一般来说,程序的栈内存空间很小,对有些题目来说,如果用普通的函数来进行递归,一旦递归层数过深(不同机器不同,约几千至几万层),则会导致程序运行崩溃。如果用栈来模拟递归算法的实现,则可以避免这一方面的问题(不过这种应用出现较少)。
三、queue
先进先出
标准库queue使用一种先进先出(first-in,first-out,FIFO)的存储和访问策略。进入队列的对象被放置队尾,而离开队列的对象从队首删除。
q.back(); //返回最后一个元素
q.empty(); //如果队列空则返回真
q.front(); //返回第一个元素
q.pop(); //删除第一个元素
q.push(); //在末尾加入一个元素
q.size(); //返回队列中元素的个数
例:
#include <iostream>
#include <queue>
using namespace std;
int main()
{
queue<int> que_data;
if (que_data.empty())
{
cout << "The que_data is empty." << endl;
}
for (int i = 0; i < 5; i++)
{
que_data.push(i * 3);
cout << que_data.back() << ' ' << que_data.size() << ' ' << endl;
}
while (!que_data.empty())
{
cout << que_data.front() << ' ' ;
que_data.pop();
}
cout << endl;
system("pause");
return 0;
}
queue不支持随机访问,即不能像数组一样地任意取值。并且,queue并不支持全部的vector的内置函数。比如queue不可以用clear()函数清空,清空queue必须一个一个弹出。同样,queue也并不支持遍历,无论是数组型遍历还是迭代器型遍历统统不支持,所以没有begin(),end();函数。