本文主要是介绍模拟实现vector中的常见接口,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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=完成深拷贝。
这篇关于模拟实现vector中的常见接口的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!