这是stl deque的测试 仅实现部分功能
这是利用首位相接的数组 [循环队列]仿stl双端队列deque
将得到一样的结果
#include<iostream>
#include<unordered_map>
using namespace std;
template<class T>
class Deque
{
int start, rear;
T* elements;
int maxsize ;
public:
Deque();
~Deque() { delete[]elements; }
bool empty();
bool isfull();
void clear();
int front();
int back();
void push_back(int x);
void push_front(int x);
void pop_back();
void pop_front();
int at(int x);
T operator[](int x);
};
template<class T>
Deque<T>::Deque()
{
maxsize = 100;
elements = new T[maxsize];
start = rear = 0;
}
template<class T>
bool Deque<T>::empty()
{
if (start == rear)
return true;
return false;
}
template<class T>
bool Deque<T>::isfull()
{
if ((rear+1)%maxsize== start)
return true;
return false;
}
template<class T>
void Deque<T>::clear()
{
start = rear = 0;
}
template<class T>
int Deque<T>::front()
{
if (!empty())
return elements[start];
else
cout << "队列为空" << endl;
}
template<class T>
int Deque<T>::back()
{
if (!empty())
{
int temp = (rear - 1 + maxsize) % maxsize;
return elements[temp];
}
else
cout << "队列为空" << endl;
}
template<class T>
void Deque<T>::push_back(int x)
{
if (!isfull())
{
elements[rear] = x;
rear=(rear+1+maxsize)%maxsize;
}
else
cout << "队列已满,不能从尾部插入" << endl;
}
template<class T>
void Deque<T>::push_front(int x)
{
if (isfull())
cout << "队列已满,不能从头部插入" << endl;
else {
start = (start - 1 + maxsize) % maxsize;
elements[start] = x;
}
}
template<class T>
void Deque<T>::pop_back()
{
if (empty())
cout << "队列为空,不能删除" << endl;
else
{
rear = (rear - 1 + maxsize) % maxsize;
}
}
template<class T>
void Deque<T>::pop_front()
{
if (empty())
cout << "队列为空,不能删除" << endl;
else
{
start = (start + 1 + maxsize) % maxsize;
}
}
template<class T>
int Deque<T>::at(int x)
{
int r = (start + x + maxsize) % maxsize;
return elements[r];
}
template<class T>
T Deque<T>::operator[](int x)
{
return elements[(start + x+maxsize)%maxsize];
}
int main()
{
Deque<int>q;
q.push_back(3);
q.push_back(4);
q.push_back(5);
q.push_back(6);
q.push_front(7);
cout << q.front() << endl;
cout << q.back() << endl;
cout << q.at(3) << endl;
cout << q[0] << endl;
q.empty();
q.pop_back();
q.pop_front();
cout << q.front() << endl;
cout << q.back() << endl;
}