insert
void insert(iterator pos, const T& x)
{
if (_finish == _endofstorage)
{
int n = pos - _start;
size_t newcapacity = capacity() == 0 ? 2 : capacity() * 2;
reserve(newcapacity);
pos = _start + n;//防止迭代器失效
}
int end = _finish-1;
while (end >= pos)
{
*(end + 1) = *(end);
--end;
}
_start[pos] = x;
++_finish;
}
push_back
void push_back(const T& x)
{
/*if (_finish == _endofstorage)
{
size_t newcapacity = capacity() == 0 ? 2 : capacity() * 2;
reserve(newcapacity);
}
*_finish = x;
++_finish;*/
insert(_finish, x);
}
erase
iterator erase(iterator pos)
{
assert(pos < _finish);
iterator it = pos;
while (it < _finish)
{
*it = *(it + 1);
++it;
}
--_finish;
return pos;
}
pop_back
void pop_back()
{
/*assert(_start < _finish);
--_finish;*/
erase(_finish_1);
}
resize
void resize(size_t n, const T& val = T())
{
if (n < _finish)
{
_finish = _start + n;
}
else
{
if (n > capacity()) reserve(n);
while (_finish<_start+n)
{
*_finish = val;
++_finish;
}
}
}
注:resize的分三种情况考虑,考虑n与_finish和_capacity的关系。
不能用memset按字节处理,会发生错误
int i = int();
int j = int(1);
double d = double();
double e = double(1.1);
vector的拷贝构造(深拷贝)
//v2(v1)
vector(const vector<T>& v)
{
_start = new T[capacity()];
-finish = _start;
_endofstorage = _start + capacity();
for (size_t i = 0; i < v.size(); ++i)
{
*_finish = v[i];
++_finish;
}
}
operator=
vector<T> operator=(const vector<T>& v)
{
if (this != &v)
{
delete[] _start;
_start = new T[capacity()];
memcpy(_start, v._start, sizeof(T) * v.size());
}
return *this;
}
现代写法
//v1=v3;
vector<T>& operator=(vector<T> v)
{
swap(_start, v._start);
swap(_finish, v._finish);
swap(_endofstorage, v._endofstorage);
return *this;
}
reserve
void reserve(size_t n)
{
if (n > capacity())
{
size_t sz = size();
T* tmp = new T[n];
if (_start)
{
memcpy(tmp, _start, sizeof(T) * sz);
/*for (size_t i = 0; i < sz; i++)
tmp[i] = _start[i];*/
delete[] _start;
}
_start = tmp;
_finish = tmp + sz;
_endofstorage = tmp + n;
}
}
memcpy只是做浅拷贝,tmp和_start指向同一快空间,delete后tmp会指向随机值,故输出随机值。
应调string的operator=完成深拷贝。