---
title: vector模板
---
```cpp=
#include <bits/stdc++.h>
using namespace std;
template <class T>
class myvector{
public:
typedef T* iterator;
typedef T& reference;
myvector():start(0),endx(0),nsize(0),ncapacity(0),storage(0){};
myvector(int size, const T& val){
if(!size){
start=0;
end=0;
nsize=0;
ncapacity=0;
storage=0;
}
else{
int total=1;
while(total<nsize){
total*=2;
}
start=new T[total];
endx=start+nsize;
storage=start+total;
total=capacity;
}
}
myvector(int size){
if(!size){
start=0;
endx=0;
nsize=0;
ncapacity=0;
storage=0;
}
else{
int total=1;
while(total<nsize){
total*=2;
}
start=new T[total];
endx=start+nsize;
storage=start+total;
total=capacity;
}
}
~myvector(){
delete[] start;
start=NULL;
endx=NULL;
storage=NULL;
nsize=0;
}
const iterator begin(){
return start;
}
const iterator end(){
return endx;
}
const int size(){
return nsize;
}
const int capacity(){
return ncapacity;
}
const bool empty(){
return (start=endx);
}
operator T(){
return this->i;
}
bool operator>(const T& other){
return (this->i>other.i) ? true : false;
}
bool operator<(const T& other){
return (this->i<other.i) ? true : false;
}
bool operator==(const T& other){
return (this->i==other.i) ? true : false;
}
bool operator!=(const T& other){
return (this->i!=other.i) ? true : false;
}
reference operator=(const T& other) {
this->i=other.i;
return *this;
}
reference operator+(const T& other){
return *(this->i+other.i);
}
reference operator-(const T& other){
return *(this->i-other.i);
}
reference operator*(const T& other){
return *(this->i*other.i);
}
reference operator/(const T& other){
return *(this->i/other.i);
}
reference operator%(const T& other){
return *(this->i%other.i);
}
reference front(){
return *start;
}
reference back(){
return *(endx-1);
}
reference at(int i){
return *(start+i);
}
void push_back(const T& x){
if(endx!=storage){
*endx=x;
nsize++;
endx++;
}
}
void pop_back(){
endx--;
nsize--;
}
void insert(int i, const T& x){
insert(i,1,x);
}
void insert(int i, int n, const T& x){
nsize+=n;
for(int index=i;index<nsize;index++){
push_back(x);
}
for(int index=i;index<end()-n;i++){
*(start+index+n)=*(start+index);
}
endx+=n;
}
void erase(int i){
erase(i,i+1);
}
void erase(int* first, int* last){
for(int index=0;index<end()-last;index++){
*(first+index)=*(last+index);
}
while(end()-first>end()-last){
pop_back();
}
}
void clear(){
erase(start,endx);
}
private:
iterator start;
iterator endx;
iterator storage;
int nsize;
int ncapacity;
};
// x->元素 i->索引值 first-last 範圍 n->數量
```