C++stack,queue,priority_queue容器(个人笔记)-程序员宅基地

技术标签: c++  笔记  

1.熟悉stack接口以及使用

stack的C++官方文档

1.1stack的接口

函数说明 接口说明
stack() 构造空的栈
empty() 检测stack是否为空
size() 返回stack中元素个数
top() 返回栈顶元素的引用
push() 将元素val压入stack中
pop() 将stack中尾部的元素弹出

1.2stack的模拟实现

//STL下的stack实现
#include<deque>
namespace ljh
{
    
	template<class T,class container=std::deque<T>>
	class stack
	{
    
		stack()
		{
    }

		void push(const T& x)
		{
    
			_c.push_back(x);
		}

		void pop()
		{
    
			_c.pop_back();
		}

		T& top()
		{
    
			return _c.back();
		}

		const T& top() const
		{
    
			return _c.back();
		}

		size_t size() const
		{
    
			return _c.size();
		}

		bool empty() const
		{
    
			return _c.empty();
		}

	private:
		container _c;
	};
}

1.3stack的一些笔试题

最小栈
在这里插入图片描述

class MinStack {
    
public:
    stack<int> _st;
    stack<int> _minst;
    MinStack()
    {
    

    }
    
    void push(int val)
    {
    
        _st.push(val);
        if(_minst.empty()||val<=_minst.top())
        {
    
            _minst.push(val);
        }
    }
    
    void pop()
    {
    
        int val=_st.top();
        _st.pop();
        if(val==_minst.top())
        {
    
            _minst.pop();
        }
    }
    
    int top()
    {
    
        return _st.top();
    }
    
    int getMin()
    {
    
        return _minst.top();
    }
};

栈的压入、弹出序列
在这里插入图片描述

class Solution {
    
public:
    bool IsPopOrder(vector<int>& pushV, vector<int>& popV)
    {
    
        stack<int> st;
        size_t pushi=0;
        size_t popi=0;
        while(pushi<pushV.size())
        {
    
            st.push(pushV[pushi++]);
            while(!st.empty()&&st.top()==popV[popi])
            {
    
                st.pop();
                popi++;
            }
        }
        return st.empty();
    }
};

逆波兰表达式
在这里插入图片描述

class Solution {
    
public:
    int evalRPN(vector<string>& tokens)
    {
    
        stack<int> st;
        for(auto &str:tokens)
        {
    
            if(str=="+"
            ||str=="-"
            ||str=="*"
            ||str=="/")
            {
    
                int right=st.top();
                st.pop();
                int left=st.top();
                st.pop();
                switch(str[0])
                {
    
                case '+':
                    st.push(left+right);
                    break;
                case '-':
                    st.push(left-right);
                    break;
                case '*':
                    st.push(left*right);
                    break;
                case '/':
                    st.push(left/right);
                    break;
                }
            }
            else
            {
    
                st.push(stoi(str));
            }
        }
        return st.top();
    }
};

栈实现队列
在这里插入图片描述

class MyQueue {
    
public:
    MyQueue()
    {
    }
    
    void push(int x)
    {
    
        _pushst.push(x);
    }
    
    int pop()
    {
    
        int ret=this->peek();
        _popst.pop();
        return ret;
    }
    
    int peek()
    {
    
        if(_popst.empty())
        {
    
            while(!_pushst.empty())
            {
    
                _popst.push(_pushst.top());
                _pushst.pop();
            }
        }
        return _popst.top();
    }
    
    bool empty()
    {
    
        return _pushst.empty()&&_popst.empty();
    }
    stack<int> _pushst;
    stack<int> _popst;
};

2.熟悉queue接口以及使用

queue的C++官方文档

2.1queue的接口

函数声明 接口说明
queue() 构造空的队列
empty() 检测队列是否为空,是返回true,否则返回false
size() 返回队列中有效元素的个数
front() 返回队头元素的引用
back() 返回队尾元素的引用
push() 在队尾将元素val入队列
pop() 将队头元素出队列

2.2queue的模拟实现

//STL下queue的实现
#include<queue>
#include<list>
namespace ljh
{
    
	template<class T,class container=std::deque<T>>
	//template<class T,class container=std::list<T>>
	class queue
	{
    
	public:
		queue()
		{
    }

		void push(const T& x)
		{
    
			_c.push_back(x);
		}

		void pop()
		{
    
			_c.pop_front();
		}

		T& back()
		{
    
			return _c.back();
		}

		const T& back()const
		{
    
			return _c.back();
		}

		T& front()
		{
    
			return _c.front();
		}

		const T& front()const
		{
    
			return _c.front();
		}

		size_t size()const
		{
    
			return _c.size();
		}

		bool empty()const
		{
    
			return _c.empty();
		}

	private:
		container _c;
	};
}

2.3queue的笔试题

队列实现栈
在这里插入图片描述

class MyStack {
    
public:
    MyStack()
    {
    }
    
    void push(int x)
    {
    
        if(!q1.empty())
        {
    
            q1.push(x);
        }
        else
        {
    
            q2.push(x);
        }
    }
    
    int pop()
    {
    
        if(!q1.empty())
        {
    
            while(q1.size()>1)
            {
    
                q2.push(q1.front());
                q1.pop();
            }
            int ret=q1.front();
            q1.pop();
            return ret;
        }
        else
        {
    
            while(q2.size()>1)
            {
    
                q1.push(q2.front());
                q2.pop();
            }
            int ret=q2.front();
            q2.pop();
            return ret;
        }
    }
    
    int top()
    {
    
        if(!q1.empty())
        {
    
            return q1.back();
        }
        else
        {
    
            return q2.back();
        }
    }
    
    bool empty()
    {
    
        return q1.empty()&&q2.empty();
    }
    queue<int> q1;
    queue<int> q2; 
};

3.熟悉priority_queue的接口以及使用(底层堆)

priority_queueC++官方文档
以下稍微看看就行:

  1. 优先队列是一种容器适配器,根据严格的弱排序标准,它的第一个元素总是它所包含的元素中最大的。
  2. 此上下文类似于堆,在堆中可以随时插入元素,并且只能检索最大堆元素(优先队列中位于顶部的元素)。
  3. 优先队列被实现为容器适配器,容器适配器即将特定容器类封装作为其底层容器类,queue提供一组特定的成员函数来访问其元素。元素从特定容器的“尾部”弹出,其称为优先队列的顶部。
  4. 底层容器可以是任何标准容器类模板,也可以是其他特定设计的容器类。容器应该可以通过随机访问迭代器访问,并支持以下操作:
    empty():检测容器是否为空
    size():返回容器中有效元素个数
    front():返回容器中第一个元素的引用
    push_back():在容器尾部插入元素
  5. 标准容器类vector和deque满足这些需求。默认情况下,如果没有为特定的priority_queue类实例化指
    定容器类,则使用vector。
  6. 需要支持随机访问迭代器,以便始终在内部保持堆结构。容器适配器通过在需要时自动调用算法函数
    make_heap、push_heap和pop_heap来自动完成此操作

3.1priority_queue的接口

优先级队列默认使用vector作为其底层存储数据的容器,在vector上又使用了堆算法将vector中元素构造成
堆的结构,因此priority_queue就是堆,所有需要用到堆的位置,都可以考虑使用priority_queue。注意:
默认情况下priority_queue是大堆。

函数声明 接口说明
priority_queue()/priority_queue(first,last) 构造一个空的优先级队列和迭代器区间构造的优先级队列
empty() 检测优先级队列是否为空,是返回true,否则返回false
top() 返回优先级队列中最大(最小元素),即堆顶元素
push(x) 在优先级队列中插入元素x
pop() 删除优先级队列中最大(最小)元素,即堆顶元素

注意:

  1. 默认情况下,priority_queue是大堆
#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(v.begin(),v.end());
 	cout << q1.top() << endl;
 	
 	// 如果要创建小堆,将第三个模板参数换成greater比较方式
 	priority_queue<int, vector<int>, greater<int>> q2(v.begin(), v.end());
 	cout << q2.top() << endl;
}
  1. 如果在priority_queue中放自定义类型的数据,用户需要在自定义类型中提供> 或者< 的重载。
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;
}

3.2priority_queue的模拟实现

#pragma once
#include<iostream>
using namespace std;

#include<vector>
//priority_queue->堆
namespace ljh
{
    
	template<class T>
	struct less
	{
    
		bool operator()(const T& left, const T& right)
		{
    
			return left < right;
		}
	};

	template<class T>
	struct greater
	{
    
		bool operator()(const T& left, const T& right)
		{
    
			return left > right;
		}
	};

	template<class T,class Container=std::vector<T>,class Compare=less<T>>
	class priority_queue
	{
    
	public:
		priority_queue()
		{
    }

		template<class InputIterator>
		priority_queue(InputIterator first, InputIterator last)
			:_con(first, last)
		{
    
			for (int i = (_con.size() - 2) / 2;i >= 0;i--)
			{
    
				adjust_down(i);
			}
		}

		void adjust_up(int child)
		{
    
			Compare com;
			int parent = (child - 1) / 2;
			while (child > 0)
			{
    
				if (com(_con[parent], _con[child]))
				{
    
					swap(_con[child], _con[parent]);
					child = parent;
					parent = (child - 1) / 2;
				}
				else
				{
    
					break;
				}
			}
		}

		void adjust_down(int parent)
		{
    
			Compare com;
			size_t child = parent * 2 + 1;
			while (child < _con.size())
			{
    
				if (child + 1 < _con.size() && com(_con[child], _con[child + 1]))
				{
    
					++child;
				}

				if (com(_con[parent], _con[child]))
				{
    
					swap(_con[child], _con[parent]);
					parent = child;
					child = child * 2 + 1;
				}
				else
				{
    
					break;
				}
			}
		}

		void push(const T& x)
		{
    
			_con.push_back(x);
			adjust_up(_con.size() - 1);
		}

		void pop()
		{
    
			swap(_con[0], _con[_con.size() - 1]);
			_con.pop_back();
			adjust_down(0);
		}

		const T& top()
		{
    
			return _con[0];
		}

		bool empty()
		{
    
			return _con.empty();
		}

		size_t size()
		{
    
			return _con.size();
		}

	private:
		Container _con;
	};
}

3.3priority_queue的笔试题

数组中第k个最大元素
在这里插入图片描述

class Solution {
    
public:
    int findKthLargest(vector<int>& nums, int k)
    {
    
        priority_queue<int> q(nums.begin(),nums.end());
        while(--k)
        {
    
            q.pop();
        }
        return q.top();
    }
};

4.容器适配器

适配器是一种设计模式(设计模式是一套被反复使用的、多数人知晓的、经过分类编目的、代码设计经验的总结)
将一个类的接口转换成客户希望的另外一个接口。

实际上STL标准库中stack和queue是容器适配器
在这里插入图片描述
在这里插入图片描述

4.1deque(了解)(双端队列)

deque(双端队列):是一种双开口的"连续"空间的数据结构,双开口的含义是:可以在头尾两端进行插入和
删除操作,且时间复杂度为O(1),与vector比较,头插效率高,不需要搬移元素;与list比较,空间利用率比
较高。
在这里插入图片描述
如果说中控数组满了,则需要扩容,但扩容的代价低

中间位置插入删除数据是整体挪动数据还是对单个buff数组扩容,实际上两种都行,第一种的buff是一样大,则[]访问会快很多
整体挪动优势:
x=i/10 确认在第几个buff
y=i%10 确认在这个buff数组的第几个位置
劣势:挪动数据代价大

单个buff数组扩容优势:
扩容代价小
劣势:数组访问[]比较麻烦

4.1.1deque的优缺点

优点:
与vector比较,deque的优势是:头部插入和删除时,不需要搬移元素,效率特别高,而且在扩容时,也不
需要搬移大量的元素
与list比较,其底层是连续空间,空间利用率比较高,不需要存储额外字段。

缺点:不适合遍历,因为在遍历时,deque的迭代器要频繁的去检测其是否移动到某段小空间的边界,导致效率低下,而序列式场景中,可能需要经常遍历,因此在实际中,需要线性结构时,大多数情况下优先考虑vector和list,deque的应用并不多,而目前能看到的一个应用就是,STL用其作为stack和queue的底层数据结构。

4.1.2为什么选择deque作为stack和queue的底层默认容器

stack是一种后进先出的特殊线性数据结构,因此只要具有push_back()和pop_back()操作的线性结构,都可以作为stack的底层容器,比如vector和list都可以;queue是先进先出的特殊线性数据结构,只要具有push_back和pop_front操作的线性结构,都可以作为queue的底层容器,比如list。
但是STL中对stack和queue默认选择deque作为其底层容器,主要是因为:

  1. stack和queue不需要遍历(因此stack和queue没有迭代器),只需要在固定的一端或者两端进行操作。
  2. 在stack中元素增长时,deque比vector的效率高(扩容时不需要搬移大量数据);queue中的元素增长
    时,deque不仅效率高,而且内存使用率高。
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/2202_75450092/article/details/137886707

智能推荐

电脑提示“由于仅部分匹配或匹配不明确,因此无法迁移设备”怎么办?_由于部分或不明确的设备匹配,无法从以前的 os 安装迁移 scsi\disk&ven_samsung-程序员宅基地

文章浏览阅读1.2k次,点赞5次,收藏9次。由于仅部分匹配或匹配不明确,因此无法迁移设备”错误可能会在将较旧的系统更新到较新的系统版本或者安装了双系统之后出现,此外,驱动程序不兼容、系统文件损坏、计算机接口故障、系统不支持出现错误的外接设备等也可能导致该错误出现。步骤2:选择左侧的【Windows更新】,点击右侧【检查更新】按钮,耐心等待Windows更新完成,之后重启计算机并查看问题是否解决。步骤2:打开设备管理器之后,选择出现错误的设备,右键点击它,并选择【卸载设备】。选择【更新和安全】。步骤1:右键点击【开始】,选择【设备管理器】。_由于部分或不明确的设备匹配,无法从以前的 os 安装迁移 scsi\disk&ven_samsung&pr

Oracle数据库TNS常见错误解决方法 _oracle tnsping常见报错-程序员宅基地

文章浏览阅读964次。1、ORA-12541:TNS:没有监听器  原因:没有启动监听器或者监听器损坏。若是前者,使用命令net start OracleOraHome10gTNSListener(名字可能有出入)即可;如果是后者,则使用“Net Configuration Assistant”工具向导之“监听程序配置”增加一个监听器即可(基本不用写任何信息,一路OK。在添加之前可能需要把所有的监听器先删!) 2、ORA-12500:TNS:监听程序无法启动专用服务器进程或ORA-_oracle tnsping常见报错

41SpringMVC - 整合MyBatis_mybatisspringmvc-程序员宅基地

文章浏览阅读267次。整合思路Dao层SqlMapConfig.xml,空文件即可,但是需要文件头。applicationContext-dao.xmla)数据库连接池b)SqlSessionFactory对象,需要spring和mybatis整合包下的。c)配置mapper文件扫描器。Service层applicationContext-service.xml包扫描器,扫描@service注解的..._mybatisspringmvc

Debian11安装HP M1136打印机+共享_debian 安装hpm1136-程序员宅基地

文章浏览阅读564次,点赞22次,收藏6次。8.链接完后,打印测试页,有时候会失败,提示缺少plug-in组件,这个要注意看提示,当你根据提示进行plug-in插件安装时,最好打开一个终端在旁边,终端会输出log,你会发现在访问一个名为:https://developers.hp.com/sites/default/files/hplip-3.23.12-plugin.run的网址上出现访问异常,其实就是下载失败而已,我们只需要把对应版本的这个网址直接复制,然后打开迅雷新建下载,地址填这个就行。,安装共享服务,安装完后,打开任意浏览器,输入。_debian 安装hpm1136

vue移动端下拉多选基于vant实现下拉多选组件_vant dropdownmenu 多选-程序员宅基地

文章浏览阅读5.5k次。转载于 https://www.cnblogs.com/kbnet/p/13754969.html1.最近需要做一个移动端多选的功能,发现vant上没有多选的下拉组件,于是决定写一个,样式如下调用部分传入值propsselect-data-opts 传入list数据,disabled 下拉是否可用checkedList 默认选中数据selectName 下拉菜单名称eventselectMutiple 选中和确定时的回调函数,注意在回调方法里修改selectname <selec_vant dropdownmenu 多选

如何编译静态库及将多个.a静态库合并成一个.a静态库_多个静态库编译成一个库-程序员宅基地

文章浏览阅读1.9w次,点赞11次,收藏37次。所使用的命令为ar1 将所有的.a库解压成.o文件ar x xx.a2 将所有的.o 文件合并成.aar rcs xx.b *.o3 编译.a 静态库1)生成对应的.o 文件 gcc -c a.c b.c2)使用ar命令合成静态库 ar crs libjson.a *.o3) 查看编译库使用的gcc 版本: strings libjson.a |grep GCC4) 调用方法: gc..._多个静态库编译成一个库

随便推点

7、SpringBoot高频面试题-程序员宅基地

文章浏览阅读5.7k次,点赞77次,收藏35次。SpringBoot高频面试题,掌握这些,吊打面试官

img宽度 全屏占满 高度和宽度一样_img 长宽顶满-程序员宅基地

文章浏览阅读1.7k次。1、写两个div盒子,父子关系<div class="image"><img :src="food.image"></div>2、样式方面(less语法).image{position: relative;width: 100%;height: 0px;padding-top: 100%; //padding-bottom都可以img{position: absolute;top: 0;left: 0;.._img 长宽顶满

js 获取两个时间范围内的所有日期 以年月日数组形式返回_js根据日期传回日期范围-程序员宅基地

文章浏览阅读347次,点赞7次,收藏8次。js 获取两个时间范围内的所有日期 以年月日数组形式返回_js根据日期传回日期范围

Unity项目源码打开教程_unity源码文件夹 怎么打开-程序员宅基地

文章浏览阅读640次,点赞8次,收藏6次。新手教程,简单易用~_unity源码文件夹 怎么打开

计算机专业最好考的职称一览表,各类专业技术职称一览表(全).doc-程序员宅基地

文章浏览阅读5k次。各类专业技术职称一览表(全)PAGEPAGE 7各类专业技术职称一览表序号系列级别及名称高级中级初级正高副高助理级员级1高教教师教授副教授讲师助教2自然科学研究研究员副研究员助理研究员研究实习员3社会科学研究研究员副研究员助理研究员研究实习员4卫生专业技术人员主任医师(药师、护师、技师)副主任医师(药师、护师、技师)主治医师(主管药师、主管护师、主管技师)医师(药师、护师、技师)医士(药士、护士..._计算机职称级别一览表

利用FIleZilla Server在局域网搭建在线点播电脑本地文件电影FTP_filezilla 直接播放-程序员宅基地

文章浏览阅读4.8k次。写在前面 设备:笔记本电脑 Iphone8(IOS11) 主路由器 TP-Link W842N 从路由器 斐讯K2软件: FileZilla Server(Windows) Ftp Manager非专业版(IOS11) 网络构建:主路由器W842N下面有2台PC,还连着一个电视盒子从路由器通过WDS桥接到主路由器,用作信号增强,从路由器下由连着我..._filezilla 直接播放

推荐文章

热门文章

相关标签