目录
queue的作用
queue是stl库提供的一种容器适配器,也就是我们数据结构中学到的队列,是非常常用的数据结构,特点是遵循LILO(last in last out,也就是后进后出)原则。
什么是容器适配器
stl中提供的类很多都叫容器,但有一些叫做容器适配器,容器适配器到底是啥呢?我们不妨先抛掉容器这两个字,先来谈谈适配器,适配器是软件设计之中的一种概念,即基于原有的接口设计适配出用户想要的接口,是一种设计模式,适配器这种设计模式提升了代码复用性以及系统扩展性,降低了代码的耦合度,是一种优秀的设计模式。那么对于容器适配器来说,就是利用已有的容器进行各种操作封装出新的类,这就叫容器适配器。
queue的接口
构造函数
cpp
explicit queue (const container_type& ctnr = container_type());
一般来说不用给参数,直接调用默认构造就行。
empty
cpp
bool empty() const;
队列的判空。
size
cpp
size_type size() const;
返回队列的元素数。
front
cpp
value_type& front();
const value_type& front() const;
返回队列的第一个元素。
back
cpp
value_type& back();
const value_type& back() const;
返回队列的最后一个元素。
queue类的实现
cpp
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<deque>
using namespace std;
namespace jiunian
{
template<class T, class container = deque<T>>
class queue
{
public:
typedef queue<T, container> Self;
//queue()
//{
//}
//queue(Self& x):
// con(x.con)
//{
//}
//~queue()
//{
//}
bool empty() const
{
return con.empty();
}
size_t size() const
{
return con.size();
}
T& front()
{
return con.front();
}
const T& front() const
{
return con.front();
}
T& back()
{
return con.back();
}
const T& back() const
{
return con.back();
}
void push(const T& val)
{
con.push_back(val);
}
void pop()
{
con.pop_front();
}
void swap(Self& x)
{
con.swap(x.con);
}
Self operator=(Self& x)
{
con = x.con;
return *this;
}
private:
container con;
};
}
queue作为一个容器适配器,实现起来相比其他容器明显简单了不少,因为其作为容器适配器只需要对其他容器的接口进行封装就行,不需要自己造轮子。实现过程一看就懂,不做过多赘述。