实现自己的一个Vector类
//vector.h
#include<iostream>
#include<string>
using namespace std;
template<typename T>
class vector
{
class proxy;
public:
vector();
~vector();
void push_back(const T&);
void pop_back();
proxy operator[](int index);
int size();
int capacity();
void reallocate(); // 重新分配内存,动态扩容
private:
T* _elems; // 指向数组中的第一个元素
T* _end; // 指向数组本身之后的元素
T* _first_free; // 指向最后一个实际元素之后的那个元素
class proxy
{
public:
proxy(vector<T>& v,int index):_v(v),_index(index){}
// 这里形参一定要是引用,传本身啊,不然最后_v._elems[_index]就是错的。浅拷贝
T& operator=(const int elem);
operator T(){ return _v._elems[_index]; }
private:
vector<T>& _v; // 这个地方也是引用
int _index;
};
};
// Vector模型
// ______________________________
// |_|_|_|_|_|____________________|
// ↑ ↑ ↑
// _elems _first_free _end
//main.cpp
#include<iostream>
#include"vector.cpp"
using namespace std;
int main()
{
vector<int> v1;
cout<<v1.size()<<" "<<v1.capacity()<<endl;
v1.push_back(1);
cout<<v1.size()<<" "<<v1.capacity()<<endl;
v1.push_back(2);
cout<<v1.size()<<" "<<v1.capacity()<<endl;
v1.push_back(3);
cout<<v1.size()<<" "<<v1.capacity()<<endl;
v1.pop_back();
cout<<v1.size()<<" "<<v1.capacity()<<endl;
v1.pop_back();
cout<<v1.size()<<" "<<v1.capacity()<<endl;
cout<<"----------------------------------"<<endl;
cout<<"v1[0]="<<v1[0]<<endl;
//v1[0] = 2;
//(v1[0]).operator=(2);
(v1.operator[](0)).operator=(2);
cout<<"after change:"<<endl;
cout<<"v1[0]="<<v1[0]<<endl;
return 0;
}
|
//vector.cpp
#include<iostream>
#include"vector.h"
#include<string.h>
using namespace std;
template<typename T>
vector<T>::vector():_elems(new T[1]),_first_free(_elems)
{
T* tmp = _elems;
_end = ++tmp;
}
template<typename T>
vector<T>::~vector()
{
delete _elems;
_elems = NULL;
}
template<typename T>
int vector<T>::size()
{
return _first_free-_elems;
}
template<typename T>
int vector<T>::capacity()
{
return _end-_elems;
}
template<typename T>
void vector<T>::reallocate()
{
int size = this->size();
T* tmp = new T[size*2];
memcpy(tmp,_elems,size*sizeof(T));
_elems = tmp;
_first_free = _elems+size;
_end = (_elems+size*2);
}
template<typename T>
void vector<T>::push_back(const T& elem)
{
if(this->size()!=this->capacity())
{
int i = (_first_free-_elems)/sizeof(T);
_elems[i] = elem;
++_first_free;
}
else if(this->size()==this->capacity())
{
this->reallocate();
int i = (_first_free-_elems)/sizeof(T);
_elems[i] = elem;
++_first_free;
}
}
template<typename T>
void vector<T>::pop_back()
{
if(this->size()!=0)
--_first_free;
}
template<typename T>
typename vector<T>::proxy vector<T>::operator[](int index)
{
return proxy(*this,index);
// 嵌套类不传引用这里出作用域释放了,后面的=什么的没错误,但是执行就报错
}
template<typename T>
T& vector<T>::proxy::operator=(const int elem)
{
_v._elems[_index] = elem;
return _v._elems[_index];
}
|