<span style="font-family:Microsoft YaHei;font-size:18px;">#include<iostream>
using namespace std;
template <typename Object>
class Vector{
public:
//构造函数,初始化数组
Vector(int initSize = 0):theSize(initSize),theCapacity(initSize+SPARE_CAPACITY){
objects = new Object[theCapacity];
}
//复制构造函数
Vector(const Vector &rhs):objects(NULL){
operator=(rhs);
}
//释放数组
~Vector(){
delete[] objects;
}
//深度复制,=符号重新定义,operator函数,this作为左值
const Vector& operator=(const Vector &rhs){
if(this!=&rhs){//不要自己复制给自己了
int k;
delete[] objects;//释放掉初始化的那个
theSize=rhs.size();
theCapacity=rhs.theCapacity;
objects = new Object[capacity()];
for(k=0;k<size();++k){
objects[k]=rhs.objects[k];
}
}
return *this;
}
void resize(int newSize){//增加当前元素个数
if(newSize>theCapacity){//大于当前容量了
reverse(2*newSize+1);//选择容量变为当前的2倍
theSize= newSize;//更新一下当前数组的大小
}
}
void reverse(int newCapacity){//增大容量
int k;
if(newCapacity<theSize)
return;
Object* oldArray=objects;
objects = new Object[newCapacity];
for(k=0;k<size();++k){
objects[k] = oldArray[k];
}
theCapacity = newCapacity;
delete[] oldArray;
}
Object& operator[](int index){//重载返回数组
return objects[index];
}
const Object& operator[](int index) const{//不变
return objects[index];
}
//顺序装入元素
void push_back(int k){
if(theSize==theCapacity){
reverse(2*theSize+1);
}
objects[theSize++]=k;
}
void pop_back(){
--theSize();
}
bool empty(){
return size()==0;
}
int capacity() const{
return theCapacity;
}
int size() const {
return theSize;
}
const Object &back() const{
return objects[theSize-1];
}
typedef Object* iterator;
typedef const Object * const_iterator;
iterator begin(){
return &objects[0];
}
const_iterator begin() const {
return &objects[0];
}
iterator end(){
return &objects[size()];
}
iterator end()const {
return &objects[size()];
}
enum{SPARE_CAPACITY};
private:
int theSize;//当前个数
int theCapacity;//数组大小
Object *objects;//通过指针变量分配内存块
};
int main()
{
Vector<int> a;
Vector<int> b;
int i=10;
for(i=0;i<5;++i){
a.push_back(i);
}
for(Vector<int>::iterator iter=a.begin();iter!=a.end();++iter){
cout<<*iter<<" ";
}
return 0;
}</span>
数据结构-Vector实现(C++)
最新推荐文章于 2024-05-20 11:31:23 发布