【C++标准模版库】模拟实现容器适配器:stack、queue、priority_queue(优先级队列)

一.容器适配器

1.什么是适配器

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

在这里插入图片描述

二.模拟实现stack和queue

在这里插入图片描述

函数说明接口说明
stack()构造空的栈
empty()检测stack是否为空
size()返回stack中元素的个数
top()返回栈顶元素的引用
push()将元素val压入stack中
pop()将stack中尾部的元素弹出
namespace xzy
{
	//Container适配转换成stack
	template<class T, class Container = vector<T>>
	//template<class T, class Container = deque<T>> STL中的模版
	class stack
	{
	public:
		stack(){} //自定义类型默认调用它的默认构造,无需写

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

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

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

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

		bool empty() const
		{
			return _con.empty();
		}
	private:
		Container _con;
	};
}

在这里插入图片描述

函数声明接口说明
queue()构造空的队列
empty()检测队列是否为空,是返回true,否则返回false
size()返回队列中有效元素的个数
front()返回队头元素的引用
back()返回队尾元素的引用
push()在队尾将元素val入队列
pop()将队头元素出队列
namespace xzy
{
	//Container适配转换成queue
	template<class T, class Container = list<T>>
	//template<class T, class Container = deque<T>> STL中的模版
	class queue
	{
	public:
		queue() {} //自定义类型默认调用它的默认构造,无需写

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

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

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

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

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

		bool empty() const
		{
			return _con.empty();
		}
	private:
		Container _con;
	};
}

注意:

  1. 为了维护stack后进先出和queue先进先出的性质,它们没有迭代器的概念。
  2. 类模版实例化时,按需实例化,使用哪些成员函数就实例化哪些,不会全部实例化,即使类内部的成员函数中调用不存在的函数,不使用该成员函数则不会实例化,编译不会报错,只有对象.成员函数调用该成员函数时,才会实例化,编译报错。

三.STL标准库中stack和queue的底层结构

虽然stack和queue中也可以存放元素,但在STL中并没有将其划分在容器的行列,而是将其称为
容器适配器,这是因为stack和queue只是对其他容器的接口进行了包装,STL中stack和queue默认
使用deque,比如:

在这里插入图片描述

四.deque(双端队列)的简单介绍

在这里插入图片描述

deque(双端队列):是一种双开口的"连续"空间的数据结构,双开口的含义是:可以在头尾两端进行插入和删除操作,且时间复杂度为O(1),与vector比较,头插效率高,不需要搬移元素;与list比较,空间利用率比较高。

在这里插入图片描述
deque并不是真正连续的空间,而是由一段段连续的小空间拼接而成的,实际deque类似于一个动态的二维数组,其底层结构如下图所示:

在这里插入图片描述

双端队列底层是一段假象的连续空间,实际是分段连续的,为了维护其“整体连续”以及随机访问的假象,落在了deque的迭代器身上,因此deque的迭代器设计就比较复杂,如下图所示:

在这里插入图片描述

那deque是如何借助其迭代器维护其假想连续的结构呢?

在这里插入图片描述
deque的缺陷:

  1. 与vector比较,deque的优势是:头部插入和删除时,不需要搬移元素,效率特别高,而且在扩容时,也不需要搬移大量的元素,因此其效率是比vector高的。
  2. 与list比较,其底层是连续空间,空间利用率比较高,不需要存储额外字段。
  3. 但是,deque有一个致命缺陷:不适合遍历,因为在遍历时,deque的迭代器要频繁的去检测其是否移动到某段小空间的边界,导致效率低下,而序列式场景中,可能需要经常遍历,因此在实际中,需要线性结构时,大多数情况下优先考虑vector和list,deque的应用并不多,而目前能看到的一个应用就是,STL用其作为stack和queue的底层数据结构。

五.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不仅效率高,而且内存使用率高。结合了deque的优点,而完美的避开了其缺陷。

六.priority_queue(优先级队列)的介绍和使用

在这里插入图片描述

  1. 优先级队列是一种容器适配器,根据严格的弱排序标准,它的第一个元素总是它所包含的元素中最大的。

  2. 此上下文类似于堆,在堆中可以随时插入元素,并且只能检索最大堆元素(优先队列中位于顶部的元素)

  3. 优先级队列被实现为容器适配器,容器适配器即将特定容器类封装作为其底层容器类,queue提供一组特定的成员函数来访问其元素。元素从特定容器的“尾部”弹出,其称为优先队列的顶部。

  4. 底层容器可以是任何标准容器类模板,也可以是其他特定设计的容器类。容器应该可以通过随机访问迭代器访问。

  5. 标准容器类vector和deque满足这些需求,默认情况下,如果没有为特定的priority_queue类实例化指定容器类,则使用vector。

  6. 需要支持随机访问迭代器,以便始终在内部保持堆结构。容器适配器通过在需要时自动调用算法函数make_heap、push_heap和pop_heap来自动完成此操作。

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

函数声明接口说明
priority_queue()构造一个空的优先级队列
priority_queue(InputIterator first, InputIterator last)迭代器构造优先级队列
empty()检测优先级队列是否为空,是返回true,否则返回false
size()返回有效数据的个数
top()返回优先级队列中最大(最小元素),即堆顶元素
push()在优先级队列中插入元素,尾插
pop()删除优先级队列中最大(最小)元素,即堆顶元素
int main()
{
	//priority_queue<int> pq; //默认大堆
	//priority_queue<int, vector<int>, less<int>> pq;  //大堆
	priority_queue<int, vector<int>, greater<int>> pq; //小堆
	pq.push(1);
	pq.push(3);
	pq.push(9);
	pq.push(7);
	pq.push(5);

	while (!pq.empty())
	{
		cout << pq.top() << " ";
		pq.pop();
	}
	cout << endl; //输出:1 3 5 7 9

	return 0;
}

七.priority_queue的模拟实现

1.前置:仿函数的介绍

在这里插入图片描述

上面的less是仿函数:本质是一个类,这个类重载operator(),它的对象可以像函数一样使用。

template<class T>
class Less //小于号
{
public:
	bool operator()(const T& x, const T& y)
	{
		return x < y;
	}
};

template<class T>
class Greater //大于号
{
public:
	bool operator()(const T& x, const T& y)
	{
		return x > y;
	}
};

int main()
{
	//类实例化对象
	Less<int> LessFunc;       
	Greater<int> GreaterFunc; 

	//仿函数:本质是一个类,这个类重载operator(),它的对象可以像函数一样使用
	cout << LessFunc(1, 2) << endl;    //有名对象
	cout << Less<int>()(1, 2) << endl; //匿名对象
	cout << LessFunc.operator()(1, 2) << endl; //本质

	return 0;
}

排序时可以用仿函数替代函数指针,如下:

//函数指针写法
int compare(int x, int y)
{
	return x > y;
}

//回调函数cmp:通过函数指针调用的函数
void BubbleSort(int* a, int n, int(*cmp)(int, int))
{
	for (int i = 0; i < n - 1; i++)
	{
		int flag = 1;
		for (int j = 0; j < n - i - 1; j++)
		{
			if (cmp(a[j], a[j + 1])) //通过函数指针回调compare函数,进行比较大小
			{
				swap(a[j], a[j + 1]);
				flag = 0;
			}
		}
		if (flag == 1)
		{
			break;
		}
	}
}

int main()
{
	int a[] = { 1,9,5,4,6,8,2,3,7 };
	BubbleSort(a, 9, compare);

	return 0;
}
//仿函数写法:本质是一个类,这个类重载operator(),它的对象可以像函数一样使用

// < 升序
template<class T>
class Less
{
public:
	bool operator()(const T& x, const T& y)
	{
		return x < y;
	}
};

// > 降序
template<class T>
class Greater
{
public:
	bool operator()(const T& x, const T& y)
	{
		return x > y;
	}
};

template<class T, class Compare>
void BubbleSort(T* a, int n, Compare com)
{
	for (int i = 0; i < n - 1; i++)
	{
		int flag = 1;
		for (int j = 0; j < n - i - 1; j++)
		{
			//if (a[j] > a[j + 1]) 直接比较大小
			if(com(a[j + 1], a[j])) //com是类的对象调用operator(), 完成比较大小
			{
				swap(a[j], a[j + 1]);
				flag = 0;
			}
		}
		if (flag == 1)
		{
			break;
		}
	}
}

int main()
{
	//类实例化对象
	Less<int> LessFunc;       // < 升序
	Greater<int> GreaterFunc; // > 降序

	int a[] = {1,9,5,4,6,8,2,3,7};

	//函数模版显示实例化传入类名,函数的参数传入类实例化的对象,也可以是匿名对象
	//BubbleSort<int, Less<int>>(a1, 9, LessFunc);    //有名对象
	//BubbleSort<int, Less<int>>(a1, 9, Less<int>()); //匿名对象
	
	//这里函数模版可以无需显示实例化,只需传入函数参数,编译器会自动推导函数模版的类型
	BubbleSort(a, 9, LessFunc);       //有名对象,升序
	BubbleSort(a, 9, Less<int>());    //匿名对象,升序
	BubbleSort(a, 9, GreaterFunc);    //有名对象,降序
	BubbleSort(a, 9, Greater<int>()); //匿名对象,降序

	return 0;
}
class Date
{
	friend ostream& operator<<(ostream& _cout, const Date& d);

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);
	}

private:
	int _year;
	int _month;
	int _day;
};

ostream& operator<<(ostream& _cout, const Date& d)
{
	_cout << d._year << "-" << d._month << "-" << d._day;
	return _cout;
}

class DateLess
{
public:
	bool operator()(Date* p1, Date* p2)
	{
		return *p1 < *p2;
	}
};

class DateGreater
{
public:
	bool operator()(Date* p1, Date* p2)
	{
		return *p1 > *p2;
	}
};

int main()
{
	//当优先级队列存储的时自定义类型时,由于内部存在比较大小,我们自己需要重载operator大于、小于号
	priority_queue<Date> q1;
	q1.push(Date(2024, 8, 29));
	q1.push(Date(2024, 8, 30));
	q1.push(Date(2024, 8, 31));

	cout << q1.top() << endl;
	q1.pop();
	cout << q1.top() << endl;
	q1.pop();
	cout << q1.top() << endl;
	q1.pop();

	cout << endl;

	//当优先级队列存储的时自定义类型的指针时,比较的是地址的大小,无意义,需要自己写仿函数
	priority_queue<Date*> q2;
	q2.push(new Date(2024, 8, 29));
	q2.push(new Date(2024, 8, 30));
	q2.push(new Date(2024, 8, 31));

	cout << *q2.top() << endl;
	q2.pop();
	cout << *q2.top() << endl;
	q2.pop();
	cout << *q2.top() << endl;
	q2.pop();

	cout << endl;
	
	//自己写仿函数,实现比较大小
	priority_queue<Date*, vector<Date*>, DateLess> q3;
	q3.push(new Date(2024, 8, 29));
	q3.push(new Date(2024, 8, 30));
	q3.push(new Date(2024, 8, 31));

	cout << *q3.top() << endl;
	q3.pop();
	cout << *q3.top() << endl;
	q3.pop();
	cout << *q3.top() << endl;
	q3.pop();

	return 0;
}

在这里插入图片描述

2.模拟实现

namespace xzy
{
	// < 升序
	template<class T>
	class Less
	{
	public:
		bool operator()(const T& x, const T& y)
		{
			return x < y;
		}
	};

	// > 降序
	template<class T>
	class Greater
	{
	public:
		bool operator()(const T& x, const T& y)
		{
			return x > y;
		}
	};
	
	template<class T, class Container = vector<T>, class Compare = Less<T>>
	class priority_queue
	{
	public:
		//对于自定义类型不需要写构造函数和析构函数,编译器会自动调用
		priority_queue(){}
		~priority_queue(){}

		//向上调整算法:维持堆的特点
		void AdjustUp(int child)
		{
			Compare cmp; //实例化对象

			int parent = (child - 1) / 2;

			while (child > 0)
			{
				//if (_con[child] > _con[parent]) 孩子 > 父亲,交换,建大堆
				if(cmp(_con[parent], _con[child]))
				{
					swap(_con[child], _con[parent]);
					child = parent;
					parent = (child - 1) / 2;
				}
				else
				{
					break;
				}
			}
		}

		//尾插
		void push(const T& x)
		{
			//尾插
			_con.push_back(x);

			//向上调整堆
			AdjustUp(size() - 1);
		}

		void AdjustDown(int parent)
		{
			Compare cmp; //实例化对象

			//假设左孩子最大
			int child = parent * 2 + 1;

			while (child < size())
			{
				//找出真正最大的那个孩子
				//if (child + 1 < size() && _con[child + 1] > _con[child])
				if (child + 1 < size() && cmp(_con[child], _con[child + 1]))
				{
					++child;
				}

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

		//头删
		void pop()
		{
			//交换堆顶与堆尾的数据
			swap(_con[0], _con[size() - 1]);

			//尾删
			_con.pop_back();

			//向下调整堆
			AdjustDown(0);
		}

		const T& top() const
		{
			return _con.front();
		}

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

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

	private:
		Container _con;
	};
}

int main()
{
	//利用仿函数可以灵活的实现大小堆
	//xzy::priority_queue<int, vector<int>, Less<int>> pq;  //大堆
	xzy::priority_queue<int, vector<int>, Greater<int>> pq; //小堆
	pq.push(15);
	pq.push(24);
	pq.push(50);
	pq.push(6);
	pq.push(19);
	pq.push(29);
	pq.push(7);

	while (!pq.empty())
	{
		cout << pq.top() << " ";
		pq.pop();
	}
	cout << endl; //输出:6 7 15 19 24 29 50

	return 0;
}

3.关于堆的算法

int main()
{
	int myints[] = { 10,20,30,5,15 };

	//vector的迭代器构造,也支持原生指针,原因是物理空间是连续的
	vector<int> v(myints, myints + 5);

	make_heap(v.begin(), v.end()); //先建堆,默认是大堆
	cout << "initial max heap   : " << v.front() << '\n';

	//堆的头删
	pop_heap(v.begin(), v.end()); //交换堆顶与堆尾的数据,再向下调整恢复成堆 
	v.pop_back(); //尾删
	cout << "max heap after pop : " << v.front() << '\n';

	//堆的尾插
	v.push_back(99); //尾插
	push_heap(v.begin(), v.end()); //向上调整恢复成堆
	cout << "max heap after push: " << v.front() << '\n';

	sort_heap(v.begin(), v.end()); //堆排序

	cout << "final sorted range :";
	for (unsigned i = 0; i < v.size(); i++)
	{
		cout << v[i] << " ";
	}
	cout << endl;

	return 0;
}

八.栈和队列OJ题

  1. 最小栈

在这里插入图片描述

class MinStack {
public:
    //1.初始化列表是成员变量定义的地方,成员变量在初始化列表中,就用初始化列表中的值
    //2.若没有初始化列表
    //  对于内置类型有缺省值就用缺省值,没有的话取决于编译器,大概率是随机值
    //  对于自定义类型自动调用它的默认构造,没有默认构造则编译错误
    //3.同理无需写析构,编译器会自动调用它的析构
    MinStack() {}
    
    void push(int val)
    {
        //val入栈_st
        _st.push(val);
       
        //若_minst为空 或者 val小于等于_minst的栈顶元素:val入栈_minst
        if(_minst.empty() || val <= _minst.top())
        {
            _minst.push(val);
        }
    }
    
    void pop() 
    {
        //若_st的栈顶元素等于_minst的栈顶元素:_minst出栈
        if(_st.top() == _minst.top())
        {
            _minst.pop();
        }

        //_st出栈
        _st.pop();
    }
    
    int top() 
    {
        return _st.top();
    }
    
    int getMin() 
    {
        return _minst.top();
    }
private:
    stack<int> _st;
    stack<int> _minst;
};
  1. 栈的压入、弹出序列

在这里插入图片描述

class Solution {
public:
    bool IsPopOrder(vector<int>& pushV, vector<int>& popV) 
    {
        stack<int> st;
        int popi = 0;

        for(auto& e : pushV)
        {
            st.push(e); //入栈
             
            //栈顶数据与出栈序列是否相等,判断是否出栈
            while(!st.empty() && st.top() == popV[popi])
            {
                st.pop();
                popi++;
            }
        }
        return st.empty(); //返回栈是否为空
    }
};
  1. 逆波兰表达式求值
  2. 用栈实现队列
  3. 用队列实现栈
  4. 二叉树的层序遍历
    在这里插入图片描述
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) 
    {
        vector<vector<int>> vv;
        queue<TreeNode*> q;
        int levelSize = 0; //记录某一层数据的个数

        if(root != nullptr) 
        {
            q.push(root);
            levelSize = 1;
        }
        
        while(!q.empty())
        {
            //当前层数据的个数,控制数据一层一层的出
            vector<int> v;
            while(levelSize--)
            {
                TreeNode* front = q.front(); //保留队头指针
                v.push_back(front->val); //尾差队头指针中的数据
                q.pop(); //出队

                if(front->left != nullptr) //左孩子不为空,入队
                {
                    q.push(front->left);
                }
                if(front->right != nullptr) //右孩子不为空,入队
                {
                    q.push(front->right);
                }
            }
            vv.push_back(v); 
            //当前层出完,下一层都进队列了,队列的size就是下一层的数据个数
            levelSize = q.size();
        }
        return vv;
    }
};
  • 18
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值