STL之queue及其底层实现

5 篇文章 2 订阅

STL之queue及其底层实现

1. 什么是queue?

queue文档(所有的接口介绍及其使用方法)

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

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

3. 底层容器可以是标准容器类模板之一,也可以是其他专门设计的容器类。该底层容器应至少支持以下操作:empty:检测队列是否为空;size:返回队列中有效元素的个数;front:返回队头元素的引用;back:返回队尾元素的引用push_back:在队列尾部入队列;pop_front:在队列头部出队列

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

queue

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

代码示例:

#include <iostream>
#include <queue>

using namespace std;

void test_queue()
{
	queue<int> q;
	q.push(1);
	q.push(2);
	q.push(3);
	q.push(4);
	q.emplace(5);

	cout << q.size() << endl;
	// queue没有迭代器
	while (!q.empty())
	{
		cout << q.front() << " ";
		q.pop();
	}
	cout << endl;
}

int main()
{
	test_queue();
	return 0;
}
3.queue没有迭代器

queue所有元素的进出都必须符合先进先出的条件,只有queue的顶端元素,才有机会被外界取用,queue不提供遍历功能,也不提供迭代器。

4.queue的模拟实现

由于queue的接口中存在头删和尾插,因此使用vector来封装效率比较低,故可以借助list来模拟实现queue。

具体实现如下

#include <list>
namespace bite
{
	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:
		std::list<T> _c;
	};
}

注:若想查看C语言版队列的实现,详见博客栈与队列

5. queue的OJ习题

使用队列实现栈的下列操作:push(x) – 元素 x 入栈 pop() – 移除栈顶元素 top() – 获取栈顶元素 empty() – 返回栈是否为空。OJ链接

思路
1. 不管底层用什么结构实现,永远保证数据先进后出的一个逻辑数据结构,即栈
2. 借助队列实现栈,可以使用两个队列,也可以只是用一个队列,本解只借助一个队列即可
3. 入栈,即把数据进行入队,为了保证栈的特性先进后出,因此需要在push方法中对入队之前的所有元素进行一次出队入队操作,以保证所有数据达到先进后出的顺序
4. 出栈,由于队列数据顺序已经调整,所以只需取队头元素即可 queue

class MyStack {
public:
    /** Initialize your data structure here. */
    MyStack() {}
    
    /** Push element x onto stack. */
    void push(int x) {
    	 // 反转队列,将新元素移至队头
        int size = q.size();
        q.push(x);
        while (size--)
        {
            q.push(q.front());
            q.pop();
        }
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() 
    {
        int element = q.front();
        q.pop();
        return element;
    }
    
    /** Get the top element. */
    int top() {
        return q.front();
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return q.empty();
    }
private:
    queue <int> q;
};
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值