C++ STL 学习笔记-适配器 stack、queue、priority_queue简单使用方法及注意事项

本文介绍了C++ STL中的三种容器适配器stack、queue、priority_queue。它们是其他容器的包装体,无迭代器,不能同时插入或删除多元素。分别阐述了三者的底层数据结构、排序方式及支持的操作,还给出了priority_queue切换数据结构的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  这个三个容器适配器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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值