实现vector
#include <iostream>
using namespace std;
template <typename T>
class Myvector
{
private:
T *first;
T *last;
T *end;
public:
//无参构造函数
Myvector(){};
Myvector(int s):first(new T(s))
{
last = first;
end = first+s;
}
//析构函数
~Myvector(){};
//拷贝构造
Myvector(const Myvector<T> &other)
{
int len = other.last-other.first;
int size = other.end - other.first;
this->first=new T[size];
memcpy(this->first,other.first,len*sizeof(T));
this->last=this->first+len;
this->end = this->first+size;
}
Myvector & operator=(const Myvector<T> & other)
{
this->first = other.first;
this->last = other.last;
this->end = other.end;
}
T &at(int n)
{
int size = last-first;
if(n > size || n < 0)
{
return NULL;
}
return first[n];
}
bool empty()
{
if(this->first == this->last)
{
return 1;
}
else
{
return 0;
}
}
bool full()
{
if(this->end == this->last)
{
return 1;
}
else
{
return 0;
}
}
T &front()const
{
return *first;
}
T &back()const
{
return *(last-1);
}
int size()
{
return last-first;
}
void clear()
{
last = first;
}
void expandsize()
{
int size = this->end - this->first;
T *temp = new T[2*size];
memcpy(temp, this->first, size*sizeof(T));
delete []first;
first = temp;
last = first+size;
end = first+2*size;
}
void push_back(const T val)
{
if(this->full())
{
this->expand();
}
*last = val;
last++;
}
void pop_back()
{
if(this->empty())
{
return;
}
--last;
}
void display()
{
T *temp= first;
while(temp < last)
{
cout << *temp << " ";
temp++;
}
cout << endl;
}
};
实现queue
#include <iostream>
using namespace std;
template <typename T>
class Queue{
private:
int head;
int tail;
T *s;
int len;
public:
Queue(){}
Queue(int h):s(new T(h)), len(h){
this->head = 0;
this->tail = 0;
}
void QuereAdd(T q){
int n = (tail+len-head)%len;
if(n < len - 1){
*(s+tail) = q;
tail = (tail+1)%len;
return ;
}
cout << "队列满" << endl;
}
void QueueDelete(){
head += 1;
}
void show(){
int first = head;
while(first != tail){
cout << *(s+first) << " ";
first = (first+1)%len;
}
cout << endl;
}
};
int main()
{
Queue<int> Q1(5);
Q1.QuereAdd(1);
Q1.QuereAdd(2);
Q1.QuereAdd(3);
Q1.show();
Q1.QueueDelete();
Q1.show();
return 0;
}