queue的模拟实现
在STL中,queue底层默认采用deque实现,且也属于容器适配器
要实现queue的一下接口:
push
pop
back
front
size
empty
#include<deque>
#include<list>
#include<iostream>
using namespace std;
template<class T, class Con = deque<T>>
class queue
{
public:
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;
};
void test() {
queue<int, deque<int>> q;
q.push(1);
q.push(2);
q.push(3);
q.push(4);
cout << q.size() << endl;
while (!q.empty()) {
cout << q.front() << endl;
q.pop();
}
}
int main() {
test();
return 0;
}
本文介绍了一种使用双端队列(deque)实现队列(queue)的方法,详细展示了队列的基本操作如push、pop、front、back、size和empty的实现过程。通过模板类的形式,演示了如何自定义队列的底层容器,提供了完整的代码示例。
1477

被折叠的 条评论
为什么被折叠?



