首先铺垫一些扩展性知识:
分离编译不会模板实例化
1)显示实例化,最好指定模板类型(因为有的模板必须指定类型)。
2)最好的方式是把声明和定义放一个头文件里(类里面定义太大了)。
构造函数:
Vector()
: _first(NULL)
, _finish(NULL)
, _endofstorage(NULL)
{}
Vector( const Vector<T>& v)
{
_first = new T[v._finish-v._first];
/*memcpy(_first, v._first,(v._finish-v._first)*sizeof(T));*/
T* start = v._first;
while (start != v._finish)
{
*(_finish) = *(start);
_finish++;
start++;
}
_finish = _first + (v._finish - v._first);
_endofstorage = _first + (v._finish - v._first);
}
Vector& operator=(const Vector& v)
{
if (this!=&v)
{
T* newstr = new T[v._finish-v._first];
delete[] _first;
_first = _finish = newstr;
/*memcpy(_first, v._first, (v._finish - v._first)*sizeof(T));*/
T*start = v._first;
while (start != v._finish)
{
*(_finish) = *(start);
_finish++;
start++;
}
_finish = _first + (v._finish - v._first);
_endofstorage = _first + (v._finish - v._first);
}
return *this;
}
~Vector()
{
if(_first)
delete []_first;
_first = _finish = _endofstorage = NULL;
}
Vector内部实现:
templateT>
void Vector<T>::Expand(size_t n)
{
if (Size() >= Capacity())
{
size_t size = Size();
T* tmp = new T[n];
T* cur = tmp;
if (_first)
{
//memcpy(tmp, _first, Size()*sizeof(T));
T*start = _first;
while (start!=_finish)
{
(*tmp) = (*start);
++tmp;
++start;
}
delete[] _first;
}
_first = cur;
_finish = _first + size;
_endofstorage = _first + n;
}
}
template<class T>
void Vector::Insert(size_t pos, const T& x)
{
assert(pos <= Size());
if (Size()>= Capacity())
{
Expand(Capacity() * 2 + 3);
}
T* end = _finish-1;
while (end >= _first + pos)
{
*(end+1) = *(end);
--end;
}
//while (end!=_finish)
//{
// *(end+1) = *end;
//}
*(_first + pos) = x;
++_finish;
}
template<class T>
void Vector<int>::Erase(size_t pos)
{
assert(pos < Size());
T* start = _first + pos + 1;
while (start < _finish)
{
*(start - 1) = *start;
++start;
}
--_finish;
}
templateT>
size_t Vector<T>::Find(const T& x)
{
T* start = _first;
while (start != _finish)
{
if (*start == x)
return start - _first;
++start;
}
return -1;
}
Vector v1;
v1.PushBack(1);
v1.PushBack(2);
v1.PushBack(3);
v1.PushBack(4);
v1.Print();
v1.Insert(0, 5);
v1.Insert(3, 6);
v1.Insert(6, 7);
printf("%d",v1.Find(3));
v1.Print();
cout << endl;
v1.Erase(2);
v1.Erase(5);
v1.Print();
cout << endl;
完成了整型测试任意位置的插入,删除,查找。
2)字符串类型测试:string
Vector v4;
v4.PushBack("hello");
v4.PushBack("world!");
v4.Print();
v4.PushBack("4444444444444444444444444");
v4.Print();
v4.PushBack("3211312434111111111111111");
v4.PushBack("23");
v4.Print();
这里进行字符串拷贝的时候要注意不能使用memcopy
原因:
错误拷法:
memcopy会导致上图错误
正确拷法:
windows下短值可拷的原因:
编译器将较小值存在数组buf中,若有一值过长,就会出问题:
所以拷值的时候为了一劳永逸,就采用如下拷贝方法:
Vector& operator=(const Vector& v)
{
if (this!=&v)
{
T* newstr = new T[v._finish-v._first];
delete[] _first;
_first = _finish = newstr;
/*memcpy(_first, v._first, (v._finish - v._first)*sizeof(T));*/
T*start = v._first;
while (start != v._finish)
{
*(_finish) = *(start);
_finish++;
start++;
}
_finish = _first + (v._finish - v._first);
_endofstorage = _first + (v._finish - v._first);
}
return *this;
}