#include <iostream>
#include <cstring>
using namespace std;
template <typename T>
class vector
{
public:
T* first;
T* last;
T* end1;
vector():first(NULL),last(NULL),end1(NULL)
{
}
vector(int num, const T &val )
{
first = new T[num];
last = first + num;
end1 = first + num;
for(int i = 0; i < num; i++)
{
*(first+i) = val;
}
}
/*
vector(const T &from)
{}
*/
vector( const T* start, const T* end2)
{
first = new T[end2-start];
end1 = first+(end2-start);
last = first;
for(int i = 0; i < (end2 - start); i++)
{
*last = *(start+i);
last++;
}
}
int size()
{
if(NULL == first)
return 0;
else
return last - first;
}
int capacity()
{
if(NULL == first)
return 0;
else
return end1 - first;
}
void push_back(const T &val)
{
if(first == NULL)
{
first = new T ;
last = first;
end1 = first + 1;
}
if(last == end1)
{
int s_ize = end1-first;
T* temp = new T[2*s_ize];
memset(temp,0,2*sizeof(T)*s_ize);
memcpy(temp,first,sizeof(T)*s_ize);
delete []first;
first = temp;
last = first + s_ize;
end1 = first + 2*(s_ize);
}
*last = val;
last = last + 1;
}
void pop_back()
{
last--;
}
T & at(int num)
{
return *(first+num);
}
T & front()
{
return *first;
}
T & back()
{
return *(first+this->size()-1);
}
T* begin()
{
return first;
}
T* end()
{
return last;
}
void clear()
{
last = first;
}
bool empty()
{
return last == first ? 1 : 0;
}
};
int main()
{
vector<int> v1; //定义一个容器
cout<<"v1.size = "<<v1.size()<<endl; //0
cout<<"v1.capacity = "<<v1.capacity()<<endl; //0
cout<<"************************************************************\n";
for(int i=1; i<=20; i++)
{
v1.push_back(i);
cout<<"v1.size = "<<v1.size()<<" v1.capacity = "<<v1.capacity()<<endl;
}
//输出当前vector中的内容
for(auto i=0; i<v1.size(); i++)
{
//cout<<v1[i]<<" ";
cout<<v1.at(i)<<" ";
}
cout<<endl;
//调用尾删函数
v1.pop_back();
for(int i=0; i<v1.size(); i++)
{
//cout<<v1[i]<<" ";
cout<<v1.at(i)<<" ";
}
cout<<endl;
//将第一个元素的值改为100,最后一个值改为200
v1.front() = 100;
v1.back() = 200;
for(int i=0; i<v1.size(); i++)
{
//cout<<v1[i]<<" ";
cout<<v1.at(i)<<" ";
}
cout<<endl;
//清空vector
v1.clear();
cout<<"v1.size = "<<v1.size()<<endl; //0
cout<<"v1.capacity = "<<v1.capacity()<<endl; //32
for(int i=0; i<v1.capacity(); i++)
{
//cout<<v1[i]<<" ";
cout<<v1.at(i)<<" ";
}
cout<<endl;
cout<<"***************************************\n";
vector<char> v2(5, 'A');
cout<<"v2.size = "<<v2.size()<<endl; //0
cout<<"v2.capacity = "<<v2.capacity()<<endl; //32
for(int i=0; i<v2.size(); i++)
{
//cout<<v1[i]<<" ";
cout<<v2.at(i)<<" ";
}
cout<<endl;
cout<<"v2.size = "<<v2.size()<<endl; //5
cout<<"v2.capacity = "<<v2.capacity()<<endl; //5
v2.push_back('G');
cout<<"v2.capacity = "<<v2.capacity()<<endl; //10
//使用别的容器给新容器初始化
int arr[] = {3,8,4,6,2,9,1,0,7};
vector<int> v3(arr, arr+5);
for(int i=0; i<v3.size(); i++)
{
//cout<<v3[i]<<" ";
cout<<v3.at(i)<<" ";
}
cout<<endl;
return 0;
}
仿Vector模板类
于 2022-12-10 15:05:52 首次发布