C++:stack和queue

stack的介绍和使用

stack的介绍

https://cplusplus.com/reference/stack/stack/?kw=stack

stack的使用

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

stack的OJ题

最小栈:

代码:

cpp 复制代码
class MinStack {
public:
    MinStack() {}
    
    void push(int val) {
        _st.push(val);
        if(_minst.empty()|| val <= _minst.top())
        {
            _minst.push(val);
        }
    }
    
    void pop() {
        if(_st.top() == _minst.top())
        {
            _minst.pop();
        }
        _st.pop();
    }
    
    int top() {
        return _st.top();
    }
    
    int getMin() {
        return _minst.top();
    }

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

栈的压入、弹出序列:

代码:

cpp 复制代码
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pushV int整型vector 
     * @param popV int整型vector 
     * @return bool布尔型
     */
    bool IsPopOrder(vector<int>& pushV, vector<int>& popV) {
        stack<int> st;

        size_t pushi = 0,popi = 0;
        while (pushi < pushV.size()) 
        {
            st.push(pushV[pushi++]);

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

逆波兰表达式求值:

代码:

cpp 复制代码
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;
                    default:
                    break;
                }
            }
            else
            {
                st.push(stoi(str));
            }
        }
        return st.top();
    }
};

stack的底层结构

push

在C语言的文章需要自己写扩容、调用指针。可是在C++可以直接使用标准库中的push_back

代码:

cpp 复制代码
void push(const T& x)
{
	_con.push_back(x);
}

pop

也可以直接使用标准库的pop_back

代码:

cpp 复制代码
void pop()
{
	_con.pop_back();
}

size

代码:

cpp 复制代码
size_t size() const
{
	return _con.size();
}

empty

代码:

cpp 复制代码
bool empty() const
{
	return _con.empty();
}

top(const版本和非const版本)

cpp 复制代码
const T& top() const
{
	return _con.back();
}

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

queue的介绍和使用

queue的介绍

https://cplusplus.com/reference/queue/queue/

翻译:

  1. 队列是一种容器适配器,专门用于在FIFO上下文(先进先出)中操作,其中从容器一端插入元 素,另一端提取元素

  2. 队列作为容器适配器实现,容器适配器即将特定容器类封装作为其底层容器类,queue提供 一组特定的成员函数来访问其元素。元素从队尾入队列,从队头出队列。

  3. 底层容器可以是标准容器类模板之一,也可以是其他专门设计的容器类。该底层容器应至少 支持以下操作:

empty:检测队列是否为空

size:返回队列中有效元素的个数

front:返回队头元素的引用

back:返回队尾元素的引用

push_back:在队列尾部入队列

pop_front:在队列头部出队列

4.标准容器类deque和list满足了这些要求。默认情况下,如果没有为queue实例化指定容器 类,则使用标准容器deque。

queue的使用

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

queue的底层结构

push

代码:

cpp 复制代码
void push(const T& x)
{
	_con.push_back(x);
}

pop

代码:

cpp 复制代码
void pop()
{
	_con.pop_front();
}

size

代码:

cpp 复制代码
size_t size() const
{
	return _con.size();
}

empty

代码:

cpp 复制代码
bool empty() const
{
	return _con.empty();
}

front(const版本和非const版本)

代码:

cpp 复制代码
const T& front() const
{
	return _con.front();
}

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

priority_queue的介绍和使用

priority_queue的介绍

https://cplusplus.com/reference/queue/priority_queue/

翻译:

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

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

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

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

empty():检测容器是否为空

size():返回容器中有效元素个数

front():返回容器中第一个元素的引用

push_back():在容器尾部插入元素

pop_back():删除容器尾部元素

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

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

priority_queue的使用

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

在OJ中的使用

代码:

cpp 复制代码
class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        priority_queue<int> pq(nums.begin(),nums.end());
        while(--k)
        {
            pq.pop();
        }

        return pq.top();
    }
};

priority_queue的模拟实现

在模拟实现中会用到在C语言数据结构中的堆结构,这个会放到后面讲

push:

cpp 复制代码
void push(const T& x)
{
	_con.push_back(x);

	adjust_up(_con.size()-1); //这个的实现放到后面说
}	

pop:

cpp 复制代码
void pop()
{
	swap(_con[0], _con[_con.size() - 1]);
	_con.pop_back();

	adjust_down(0); //这个也放到后面说
}

top、empty、size:

cpp 复制代码
const T& top()
{
	return _con[0];
}

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

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

仿函数

仿函数又叫"函数对象",仿函数可以将函数当作参数使用,只需要重载"operator()"就好,这里使用刚才的adjust_up和adjust_down来举例,不过在这之前我们先写两个仿函数

cpp 复制代码
template<class T>
class Less
{
public:
	bool operator()(const T& x, const T& y)
	{
		return x < y;
	}
};

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

接下来把adjust_up和adjust_down函数写上

cpp 复制代码
void adjust_up(int child)
{
	Compare com;

	int parent = (child - 1) / 2;
	while (child > 0)
	{
		//if (_con[child] > _con[parent])
		//if (_con[parent] < _con[child])
		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 = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}

在没有使用仿函数以前我们写adjust_up和adjust_down每次要排升序和降序时都要更换if中的大于和小于符号,当我使用仿函数后就不需要一直更改,只要在模板参数里加上"class Compare = Less<T>",这样就是降序

cpp 复制代码
template<class T,class Container = vector<T>,class Compare = Less<T>>

把Less改成Gearter就是升序

cpp 复制代码
template<class T,class Container = vector<T>,class Compare = Gearter<T>>
相关推荐
烟烟Abandon2 小时前
FFmpeg开发基础之 C 语言 :再论指针(讲透指针)
c语言·开发语言·ffmpeg
风中的微尘5 小时前
数学基础2
算法
阿俊-全栈开发5 小时前
扩展设计解析:LikeShop Go 版商城营销活动的插件化扩展设计思路
开发语言·微服务·golang·likeshop·likeshop源码
干啥啥不行,bug第一名5 小时前
EAFNOSUPPORT、EPROTOTYPE、EOPNOTSUPP:socket 的三层参数没有对齐
开发语言·php
fqbqrr5 小时前
2612,现代cmake
c++·cmake
丽丽的代码5 小时前
Docker 命令学习手册:从零接手一个容器化项目
学习·docker·容器
一只小小的芙厨6 小时前
树状数组总结
数据结构·算法
我要见SA姐16 小时前
用生活化类比当钥匙,一键打开 C++ 入门大门
java·开发语言·c++
1024奇点6 小时前
第四篇 第 03 课
开发语言·ide·后端