本文的代码主要实现了vector 的
1.基本操作如: push_back(), pop_back(), size(), back()
2.操作符的重载如: [],=
vector的定义及实现
#include<iostream>
using namespace std;
template<typename Object>
class MyVector {
public:
//构造函数
MyVector(int initSize=0):theSize(initSize),theCapacity(initSize+SPACE_CAPACITY){
object = new Object[theCapacity];
}
//复制构造函数
MyVector(const MyVector& rhs):object(NULL){
operator=(rhs);
}
//析构函数
~MyVector() {
delete[]object;
}
//操作符=重载
const MyVector &operator=(const MyVector& rhs){
if (this != &rhs) {
delete[]object;
thesize = rhs.size();
theCapacity = rhs.capacity();
object = new Object[theCapacity];
for (int k = 0; k < theSize; k++) {
object[k] = rhs.object[k];
}
}
return *this;
}
//重载操作符[]
Object& operator[](int index) {
/*
//异常处理
if (index < 0 || index >= theSize) {
throw "检查取值范围,取值范围应该在0-theSize-1之间";
}
*/
return object[index];
}
const Object & operator[](int index)const {
return object[index];
}
//判断是否为空
bool empty() const{
return thesize == 0;
}
//长度
int size()const {
return theSize;
}
//容量
int capacity() const{
return theCapacity;
}
//重置大小
void resize(int newsize) {
if (newsize>theCapacity) {
reserve(2*newsize+1);
}
theSize = newsize;
}
//重置容量
void reserve(int newCapacity) {
if(newCapacity<theCapacity){
return;
}
Object *oldobject = object;
object = new Object[newCapacity];
for (int k = 0; k < theSize; k++) {
object[k] = oldobject[k];
}
delete[]oldobject;
theCapacity = newCapacity;
}
void push_back(const Object& x) {
if (theSize == theCapacity) {
reserve(2 * theCapacity + 1);
}
object[theSize++] = x;
}
void pop_back() {
theSize--;
}
const Object& back()const {
return object[theSize - 1];
}
enum {SPACE_CAPACITY=16};
private:
int theSize;
int theCapacity;
Object * object;
};
vector测试
void MyVectorTest() {
//
MyVector<int> vector1;
cout << "size of vector1 is : "<<vector1.size() << endl;
for (int i = 0; i < 10; i++) {
vector1.push_back(i);
}
cout << "size of vector1 is : " << vector1.size() << endl;
for (int i = 0; i < vector1.size(); i++) {
cout << vector1[i] << " ";
}
cout << endl;
vector1.pop_back();
cout << "size of vector1 is : " << vector1.size() << endl;
//
MyVector<int> vector2(3);
cout << "size of vector2 is : "<<vector2.size() << endl;
}
测试结果
ps:实现操作符[]重载时,未做异常处理