C++小白的逆袭之路——初阶(第十一章:stack和queue)


1. stack


1.1 stack的介绍和使用


1. 介绍:

  • stack是一种容器适配器,专门用在具有后进先出操作的上下文环境中,其删除只能从容器的一端进行,元素的插入与提取操作也只能从一端进行。
  • stack是作为容器适配器被实现的,容器适配器是对特定类封装作为其底层的容器,并提供一组特定的成员函数来访问其元素。将特定类作为其底层的,元素在特定容器的尾部(即栈顶)被压入和弹出。
  • stack的底层容器可以是任何标准的容器类模板或者一些其他特定的容器类,这些容器类应该支持以下操作:
    • empty:判空操作;
    • back:获取尾部元素操作;
    • push_back:尾部插入元素操作;
    • pop_back:尾部删除元素操作。
  • 标准容器vectordequelist均符合这些需求,默认情况下,如果没有为stack指定特定的底层容器,使用deque

2. 使用:

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

1.2 练习


1. 最小栈:

class MinStack {
public:
    /** initialize your data structure here. */
    MinStack() {}
    
    void push(int x) {
        _st.push(x);
        if(_minst.empty() || x <= _minst.top())
            _minst.push(x);
    }
    
    void pop() {
        if(_minst.top() == _st.top())
            _minst.pop();
        _st.pop();
    }
    
    int top() {
        return _st.top();
    }
    
    int getMin() {
        return _minst.top();
    }

    stack<int> _st;
    stack<int> _minst;
};

使用双栈来解决这个问题,一个栈_st正常压入数据,一个栈_minst用来记录_st栈当前的最小元素。

最开始_st为空,_minst也为空,所以第一个元素可以直接入栈(假设现在将序列[3,2,2,4,5]入栈)。

在这里插入图片描述

然后不断将数据压入栈_st,但是在压入前先和_minst的栈顶元素作比较,如果小于等于_minst的栈顶元素,就将数据也压入_minst栈。_st中的元素出栈时,也要先和_minst的栈顶元素比较,如果相等,那么_minst也执行出栈操作,这样就能保证_minst一直维护_st中的最小元素了。

注意这里一定是小于等于,不能是小于。因为如果有多个一样的元素被压入_st,它们又恰巧是最小的,这时如果pop_st栈中的一个最小元素,_minst也跟着pop,最小值就从_minstpop走了。

2. 验证栈的序列:

解法一:匹配了再入栈

class Solution {
public:
    bool validateStackSequences(vector<int>& pushed, vector<int>& popped)
    {
        stack<int> st;
        int j = 0; // 追踪out
        for (int i = 0; i < pushed.size(); i++)
        {
            if (pushed[i] == popped[j]) j++;
            else if (st.empty() || st.top() != popped[j]) st.push(pushed[i]);
            else {
                st.pop();
                j++;
                i--;
            }
        }

        // pushed数组已超
        while (j < popped.size())
        {
            // 若st空了直接返回真
            if (st.empty()) return true;

            if (st.top() == popped[j])
            {
                st.pop();
                j++;
            }
            else
                return false;
        }
        return true;
    }
};

解法二:不管匹不匹配先入栈

class Solution {
public:
    bool validateStackSequences(vector<int>& pushed, vector<int>& popped)
    {
        stack<int> st;
        size_t pushi = 0, popi = 0;
        while(pushi < pushed.size())
        {
        	// 先入栈
            st.push(pushed[pushi++]); 

            while(!st.empty() && st.top() == popped[popi])
            {
                st.pop();
                popi++;
            }
        }

        return st.empty();
    }
};

这个题大家可以试着分析一下,复杂了一点,但是难度不大。


1.3 stack模拟实现


这里stack的底层容器我们选择了vector,当然这不是唯一选择。在学习适配器时,会介绍stack真正的底层容器deque

#pragma once

#include<iostream>
#include<vector>

using namespace std;

template<class T>
class stack
{
public:
	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:
	vector<T> _c;
}

2. queue


2.1 queue的介绍和使用


1. 介绍:

  • 队列是一种容器适配器,专门用于在FIFO上下文(先进先出)中操作,其中从容器一端插入元素,另一端提取元素。
  • 队列作为容器适配器实现,容器适配器将特定容器类封装作为其底层容器类,queue提供一组特定的成员函数来访问其元素。元素从队尾入队列,从队头出队列。
  • 底层容器可以是标准容器类模板之一,也可以是其他专门设计的容器类。该底层容器应至少支持以下操作:
    • empty:检测队列是否为空;
    • size:返回队列中有效元素的个数;
    • front:返回队头元素的引用;
    • back:返回队尾元素的引用;
    • push_back:在队列尾部入队列;
    • pop_front:在队列头部出队列。
  • 标准容器类dequelist满足了这些要求。默认情况下,如果没有为queue实例化指定容器类,则使用标准容器deque

2. 使用:

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

2.2 练习


1. 二叉树的层序遍历:

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root)
    {
        queue<TreeNode*> q;
        int levelSize = 0;
        if (root)
        {
            q.push(root);
            levelSize = 1;
        }

        vector<vector<int>> vv;
        
        while (!q.empty())
        {
            vector<int> v;
            while (levelSize--)
            {
                TreeNode* front = q.front();
                q.pop();

                v.push_back(front->val);

                if (front->left)
                {
                    q.push(front->left);
                }
                
                if (front->right)
                {
                    q.push(front->right);
                }
            }
            vv.push_back(v);
            // 队列中的数据就是下一层的数据
            levelSize = q.size();
        }

        return vv;
    }
};

层序遍历利用队列就很好实现,但是如何控制每行的输出,才是本题的难点。我们可以设计一个变量levelSize来记录每一层的节点个数,遍历到新的一层,就将leveSize刷新,并且让leveSize随着这一层结点的输出依次--


2.3 queue模拟实现


这里底层容器选用了list

#pragma once

#include<iostream>
#include<list>

using namespace std;

template<class 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:
 	list<T> _c;
};

3. 容器适配器


3.1 容器适配器的概念


1. 什么是适配器?

  • 适配器是一种设计模式,该种模式是将一个类的接口转换成客户希望的另外一个接口。
  • stackqueue就是容器适配器,他们仅仅是套用了别的容器的接口,在STL中并不被称为容器。

在这里插入图片描述

大家来看一个具体的例子:

#pragma once
#include<vector>
#include<iostream>

using namespace std;

template<class T, class Container = vector<T>>  // 支持缺省
class stack
{
public:
	void push(const T& x)
	{
		_con.push_back(x);
	}

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

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

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

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

private:
	Container _con;
};

我们在设计stack时,不用把它的底层容器写死,可以抽象出一个容器_con,只要这个容器有上面代码中的所用到的方法,那么在实例化stack时就可以使用这个容器。例如:stack<int, vector<int>> st;,实例化出一个底层容器是vetor<int>stack

模版参数也可以使用缺省参数,这样,在我们不传stack<int, vector<int>> st;中的vector<int>,只写stack<int> st;时,stack的底层容器就默认使用我们设置的缺省值。

像通过上面这种模式设计的数据结构,我们就可以称之为容器适配器。虽然stackqueue中也可以存放元素,但在STL中并没有将其划分在容器的行列,而是将其称为容器适配器,这是因为stack和队列只是对其他容器的接口进行了包装。

2. stack和queue的底层容器:

  • stackqueue的底层容器实际上是deque。我们可以在Cplusplus上查看。

在这里插入图片描述

在这里插入图片描述


3.2 deque的简单介绍


1. deque原理介绍:

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

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

  • deque的数据空间由一个一个buffer(连续的物理空间,小定长数组)拼接而成,这些物理空间又统一由一个中控数组来维护。每一个buffer的大小固定,中控数组的本质实际上是一个指针数组,存储每一个buffer的地址,指向他们。

  • 如果要执行头插,就先挪动中控数组的数据,统一向后移,然后开一个新的buffer,让中控数组的头位置指向它,在这个新buffer的末尾插入数据。再头插,就在buffer最后一个数据的前面插入。直到新buffer也满了,再挪动中控数组,再开一个buffer,执行相同的操作。

  • 如果要尾插,先看最后一个buffer满了没有,没有就挨着插入,满了就新开buffer,再插入。

  • 迭代器:
    在这里插入图片描述

  • deque的迭代器实现较为复杂,它有四个指针,node指向中控数组中对应buffer的指针,first指向buffer中第一个数据的位置,last指向buffer中最后一个数据的下一个位置,cur指向buffer当前数据所在位置(左闭右开理念)。

2. deque的缺陷:

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

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

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

    • stackqueue不需要遍历(因此stackqueue没有迭代器),只需要在固定的一端或者两端进行操作。
    • stack中元素增长时,dequevector的效率高(扩容时不需要搬移大量数据);queue中的元素增长时,deque不仅效率高,而且内存使用率高。
  • 结合了deque的优点,而完美的避开了其缺陷。


3.3 STL库中对stack和queue的模拟实现


1. stack的模拟实现:

#pragma once

#include<iostream>
#include<deque>

using namespace std;

template<class T, class Con = deque<T>>
class stack
{
public:
	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:
	Con _c;
}

2. queue的模拟实现:

#pragma once

#include<iostream>
#include<deque>

using namespace std;

template<class T, class Con = deque<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:
 	Con _c;
};

4. priority_queue


4.1 priority_queue的介绍和使用


1. 介绍:

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

2. 使用:

  • 优先级队列默认使用vector作为其底层存储数据的容器,在vector上又使用了堆算法将vector中元素构造成堆的结构,因此priority_queue就是堆,所有需要用到堆的位置,都可以考虑使用priority_queue。注意:默认情况下priority_queue是大堆。
函数声明接口说明
priority_queue()构造一个空的优先级队列
priority_queue(first, last)用迭代器区间初始化
empty()检测优先级队列是否为空,是返回true,否则返回false
top()返回优先级队列中最大(最小元素),即堆顶元素
push(x)在优先级队列中插入元素x
pop()删除优先级队列中最大(最小)元素,即堆顶元素
  • 默认是大堆,传入greater参数,改为小堆:
#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;
 	for (auto& e : v)
 		q1.push(e);
 	cout << q1.top() << endl;
 
 	// 如果要创建小堆,将第三个模板参数换成greater比较方式,按大于号比较
 	priority_queue<int, vector<int>, greater<int>> q2(v.begin(), v.end());
 	cout << q2.top() << endl;
}
  • 如果在priority_queue中放自定义类型的数据,用户需要在自定义类型中提供>或者<的重载:
#include <vector>
#include <queue>
#include <functional> // greater算法的头文件

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);
 
private:
 	int _year;
 	int _month;
 	int _day;
};
 
ostream& operator<<(ostream& _cout, const Date& d)
{
	_cout << d._year << "-" << d._month << "-" << d._day;
	return _cout;
}

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;
}
  • 发现问题:如果priority_queue中存放的数据类型是Date*,我们的实际需求是希望优先级队列根据Data*指针找到实例化的Data来建堆,不是根据指针大小建堆,该怎么办?(答案在模拟实现后揭晓)
void TestPriorityQueue()
{
    // 每次堆顶的结果都不同,因为指针的大小是随机的
    priority_queue<Date*> q3;
    q3.push(new Date(2018, 10, 29));
    q3.push(new Date(2018, 10, 28));
    q3.push(new Date(2018, 10, 30));
    cout << *(q3.top()) << endl;
}

4.2 初识仿函数


在C++中,仿函数(Functor)是一种特殊的对象,它重载了函数调用操作符 operator(),使得对象可以像函数一样被调用。仿函数是一种将操作封装在对象中的方法,它允许我们通过对象来模拟函数的行为。

来看一个仿函数的例子:

#include <iostream>
using namespace std;

// 定义一个简单的仿函数类
template<class T>
class SimpleFunctor {
public:
    // 重载函数调用操作符
    T operator()(const T x, const T y) const 
    {
        return x + y;
    }
};

int main() 
{
    // 创建仿函数对象
    SimpleFunctor sf;
    // 使用仿函数对象
    int result = sf(3, 5);
    cout << "Result: " << result << endl; // 输出 8
    return 0;
}

在这个例子中,SimpleFunctor类重载了operator(),使其能够接受两个整数参数并返回它们的和。然后在main函数中,我们创建了一个SimpleFunctor对象,并像调用函数一样使用它。

仿函数还可以配合模版使用,提高了泛化能力,是一个非常好用的工具。

仿函数真正的价值是代替了C语言中的函数指针,可以实现C语言中函数指针的功能。函数指针的一个明显缺陷就是,类型非常难以阅读,可读性差。C++为了避开C语言中这一缺陷,设计了仿函数。


4.3 priority_queue的模拟实现


1. 优先级队列就是堆,此处只需要对堆进行封装即可:

#pragma once
#include<iostream>
#include<vector>

using namespace std;

namespace my_priority_queue
{
	// 仿函数
	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;
		}
	};

	// Compare是比较方法,默认是less方法
	template<class T, class Container = vector<int>, 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; // 因为child 和 _con.size() 比较了,为了保持类型一至,使用size_t
			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 = parent * 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();
		}

	private:
		Container _con;
	};
}
  • 提供两个仿函数lessgreater,这两个仿函数就是两个不同的比较方法。
  • 重点关注priority_queue中的最后一个模版参数Compare,这是一个比较方法,需要传一个仿函数进去,默认是less。当然这个比较方法也可以自己定义。

2. 回顾4.1中的问题:

void TestPriorityQueue()
{
    // 每次堆顶的结果都不同
    my_priority_queue::priority_queue<Date*> q3;
    q3.push(new Date(2018, 10, 29));
    q3.push(new Date(2018, 10, 28));
    q3.push(new Date(2018, 10, 30));
    cout << *(q3.top()) << endl;
}
  • 发现每次堆顶的数据都不一样,因为priority_queue是根据指针大小来建堆的,而指针大小又是随机的。这就需要仿函数上场了。
class PDataCompare
{
public:
    bool operator()(const Date* p1, const Date* p2)
    {
        return *p1 > *p2;
    }
};

void TestPriorityQueue()
{
    // 传一个自定义的比较方法
    my_priority_queue::priority_queue<Date*, vector<Date*>, PDataCompare> q3;
    q3.push(new Date(2018, 10, 29));
    q3.push(new Date(2018, 10, 28));
    q3.push(new Date(2018, 10, 30));
    cout << *(q3.top()) << endl;
}
  • priority_queue在设计时,比较方法的接口实际上是向程序员放开的,为了解决上面的问题,需要我们自己提供一个适用于Data*类型数据的比较方法。

4.4 练习


第K个最大数:

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k)
    {
        priority_queue<int> pq(nums.begin(), nums.end());
        while(--k)  // 不是k--,这里 pop k-1 次
            pq.pop();
        
        return pq.top();
    }
};

  • 14
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

-指短琴长-

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值