2023/4/3 vector和循环队列
#include <iostream>
using namespace std;
template <typename T>
class Myvector
{
private:
T * first;
T * last;
T * end;
public:
Myvector(int size = 2)
{
first = new T[size];
first = last;
end = first + last;
}
~Myvector()
{
delete [] first;
first = last = end = nullptr;
}
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<T> &operator=(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;
return *this;
}
T &at(int pos)
{
if(pos < 0 || pos > this->len())
{
cout << "越界" << endl;
}
return *(first+pos);
}
bool empty()
{
return last == first ? true:false;
}
bool full()
{
return end == last ? true:false;
}
const T& front()const
{
return *first;
}
const T& back()const
{
return *(last-1);
}
int size()const
{
return end - first;
}
int len()const
{
return last - first;
}
void clear()
{
last = first;
}
void expand()
{
int size = this->end - this->first;
T *temp = new T[2*size];
memcpy(temp->first,first,size*sizeof(T));
delete []this;
first = temp;
last = first + size;
end = first + 2*size;
}
void push_back(const T&other)
{
if(this->full())
{
this->expand();
}
*last = other;
last ++;
}
void pop_back()
{
if(this->empty())
{
return;
}
--last;
}
};
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 empty()const
{
return front==rear;
}
bool full()const
{
return (rear+1)%maxSize==front;
}
void dequeue()
{
if(empty())
{
throw ;
}
front=(front+1)%maxSize;
}
void enqueue(const T& val)
{
if(full())
{
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;
}
};