1.vector
#include <iostream>
#include <cstring>
using namespace std;
template<typename T>
class MyVector
{
private:
T* first;
T* last;
T* end;
public:
//构造
MyVector():first(nullptr),last(nullptr),end(nullptr){}
MyVector(int num,const T& val):first(new T[num])
{
for(int i=0;i<num;i++)
{
first[i]=val;
}
last=end=first+num;
}
//析构
~MyVector()
{
delete [] first;
}
//拷贝构造
MyVector(const MyVector& from):first(new T[from.end-from.first])
{
last=first+(from.last-from.first);
end=first+(from.end-from.first);
memcpy(first,from.first,(last-first)*sizeof (T));
}
//拷贝赋值
MyVector& operator=(const MyVector& from)
{
delete [] first;
first=new T[from.last-from.first];
last=first+(from.last-from.first);
end=first+(from.end-from.first);
memcpy(first,from.first,(last-first)*sizeof (T));
return *this;
}
//at() 返回指定位置的元素
T& at(int loc)
{
if(loc<0||loc>=last-first)
{
throw range_error("loc");
}
return first[loc];
}
//empty() 判断Vector是否为空(返回true时为空)
bool empty()
{
return last==first?true:false;
}
//full() 判断Vector是否为满(返回true时为满)
bool full()
{
return last==end?true:false;
}
//front() 返回第一个元素
T& front()
{
return *first;
}
//back() 返回最末一个元素
T& back()
{
return *(end-1);
}
//size() 返回Vector元素数量的大小
int size()
{
return last-first;
}
//clear() 清空所有元素
void clear()
{
last=first;
}
//expand() 二倍扩容函数
void expand()
{
int size=end-first;
MyVector tmp;
tmp.first=new T[size*2];
memcpy(tmp.first,first,size*sizeof(T));
delete [] first;
first=tmp.first;
last=first+size;
end=first+2*size;
}
//push_back() 在Vector最后添加一个元素
void push_back(const T& val)
{
if(full())
{
expand();
}
*last++=val;
}
//pop_back() 移除最后一个元素
void pop_back()
{
if(empty())
throw ;
last--;
}
void show()
{
for(auto i=this->first;i<this->last;i++)
{
cout<<*i<<" ";
}
cout<<endl;
}
};
int main()
{
MyVector<int> a(10,1);
a.show();
MyVector<int> b=a;
b=a;
b.show();
b.push_back(3);
b.show();
return 0;
}
2.循环顺序队列
#include <iostream>
using namespace std;
template<typename T>
class MyQueue
{
private:
T* queue;
size_t maxSize;
size_t front;
size_t rear;
public:
MyQueue(size_t s):queue(new T[s]),maxSize(s),front(0),rear(0){}
~MyQueue()
{
delete [] queue;
}
bool isEmpty()const
{
return front==rear;
}
bool isFull()const
{
return (rear+1)%maxSize==front;
}
void dequeue()
{
if(isEmpty())
{
throw ;
}
front=(front+1)%maxSize;
}
void enqueue(const T& val)
{
if(isFull())
{
throw ;
}
queue[rear]=val;
rear=(rear+1)%maxSize;
}
int size() const
{
return (rear+maxSize-front)%maxSize;
}
void show()const
{
for(int i=0;i<size();i++)
{
cout<<queue[i]<<" ";
}
cout<<endl;
}
};
int main()
{
MyQueue<int> q(10);
for(int i=0;i<9;i++)
{
q.enqueue(i);
}
cout<<boolalpha<<q.isFull()<<endl;
q.show();
q.dequeue();
q.show();
q.dequeue();
q.show();
cout<<boolalpha<<q.isEmpty()<<endl;
return 0;
}