最近在看数据结构,于是乎就自动动手写个简单的Vector:
#ifndef _CUSTOM_STRUCT
#define _CUSTOM_STRUCT
#define CAPACITY_VOLUMN 1000
template<class object>
class CustomVector
{
typedef object* iterator;
typedef object* const const_iterator;
private:
int size;
int capacity;
object* objects;
void Reserve(int newSize)
{
object* oldObjects = objects;
objects = new object[capacity];
for (int i=0;i<Size();i++)
{
objects[i] = oldObjects[i];
}
delete[] oldObjects;
}
public:
explicit CustomVector(int initSize = 0) : size(0),capacity(initSize*2 + CAPACITY_VOLUMN)
{
objects = new object[capacity];
}
CustomVector(const CustomVector& rhs)
{
operator=(rhs);
}
object& operator=(const CustomVector& rhs)
{
if (this != &rhs)
{
this.size = rhs.Size();
this.capacity = rhs.Capacity();
for (int i=0;i< rhs.Size();i++)
{
objects[i] = rhs[i];
}
}
}
object& operator[](int index)
{
return objects[index];
}
const object& operator[](int index) const
{
return objects[index];
}
int Size() const
{
return size;
}
int Capacity() const
{
return capacity;
}
bool Empty() const
{
return size ==0;
}
void ReSize(int newSize)
{
if (newSize > Capacity())
{
capacity = newSize;
Reserve(newSize);
}
}
void push_back(const object& obj)
{
//在添加元素之前,先检查容量
if (size > capacity)
{
capacity = capacity*2 + 1;
Reserve(capacity);
}
objects[size++] = obj;
}
void pop_back()
{
//删除元素,检查当前剩余元素个数
if (size > 0)
{
--size;
}
}
const object& back() const
{
return objects[size-1];
}
iterator begin()
{
return &objects[0];
}
const_iterator begin() const
{
return &objects[0];
}
iterator end()
{
return &objects[size-1];
}
const_iterator end() const
{
return &objects[size-1];
}
};
#endif
CustomVector使用:
#include <iostream>
#include <iomanip>
#include <vector>
#include "CustomVector.hpp"
using namespace std;
int main(int argc,char** argv)
{
CustomVector<int> vec(5);
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
vec[1] = 13;
cout << vec[1] << " " << vec[2] << std::endl;
return 0;
}