这个三个容器适配器stack、queue、priority_queue 都是包含了vector、list、deque中某个容器的包装体,也可以看作是由其他容器实现的容器,适配器没有提供迭代器,也不能同时插入或删除多个元素
stack
1.底层数据结构: 可以为:vector、deque、list 默认为deque
2.实现后进先出的值排序(栈结构)
3.支持的操作主要有:
push() 将元素压入栈
pop() 弹出栈顶元素(无返回值)
top() 获取栈顶元素 (不弹出)
empty() 栈为空返回1,不为空返回0
size() 返回栈中元素的个数
#include "stdafx.h"
#include <stack>
#include <vector>
#include <iostream>
using namespace std;
using std::stack;
using std::cout;
int _tmain(int argc, _TCHAR* argv[])
{
// stack<int> s; //默认为deque
stack<int,vector<int>> s; //使用vector
s.push(1);
s.push(64);
s.push(90);
s.push(30);
s.push(50);
while(!s.empty())
{
cout << s.top() << " ";
s.pop();
}
cout << endl;
return 0;
}
queue
1.底层数据结构:可以为list、deque,不能为vector(vector没有提供头部操作函数) 默认为:deque
2. 实现先进先出的值排序 (队列结构)
3. 支持的主要操作:
push() 将元素压入队列
pop() 弹出首部元素
front() 获取首部元素
back() 获取尾部元素
empty() 队列为空返回1,不为空返回0
size() 获取队列中元素的个数
#include "stdafx.h"
#include <queue>
#include <list>
#include <iostream>
using namespace std;
using std::queue;
using std::cout;
int _tmain(int argc, _TCHAR* argv[])
{
//queue<int> q;
queue<int,list<int>> q;
q.push(4);
q.push(6);
q.push(8);
q.push(40);
q.push(400);
q.push(35);
while(!q.empty())
{
cout << q.front() << " ";
q.pop();
}
cout <<endl;
return 0;
}
priority_queue
1.底层数据结构:可以为:vector、deque 不能为list(因为priority_queue要求对元素随机访问以便排序),默认数据结构为:deque
2.采用有序顺序排序,但不采用严格的先进先出的顺序,而是按照优先级,给定队首的元素正是优先级最高的元素,如果两个元素有相同的优先级,那么他们在队列中的排列顺序是遵循先进先出的
3.支持的操作主要有:
push() 将元素压入队列
pop() 弹出首部元素(无返回值)
top() 获取首部元素(不弹出)
empty() 队列为空返回1,队列不为空返回0
size() 获取队列中元素的个数
4.切换数据结构的方法: 以int为例
prioriry_queue<int,vector<int>> pq;
#include "stdafx.h"
#include <queue>
#include <iostream>
using namespace std;
using std::queue;
using std::cout;
int _tmain(int argc, _TCHAR* argv[])
{
//less<int> 大值先出队 greater<int> 小值先出队
priority_queue<int,vector<int>,less<int>> pq;
pq.push(101);
pq.push(2);
pq.push(45);
pq.push(25);
pq.push(6);
while(!pq.empty())
{
cout << pq.top()<<" ";
pq.pop();
}
cout <<endl;
return 0;
}