namespace bing
{
template<class T>
class vector {
public:
typedef T* iterator;
typedef const T* const_iterator;
iterator begin() {
return _start;
}
iterator end() {
return _finish;
}
const_iterator cbegin() const {
return _start;
}
const_iterator cend() const {
return _finish;
}
// construct
vector()
:_start(nullptr)
, _finish(nullptr)
, _endofstorage(nullptr)
{}
vector(int n, const T& value = T())
:_start(nullptr)
, _finish(nullptr)
, _endofstorage(nullptr)
{
reserve(n);
while (n) {
push_back(value);
n--;
}
}
template<class InputIterator>
vector(InputIterator first, InputIterator last) {
reserve(last - first);
while (first != last) {
push_back(*first);
++first;
}
}
vector(const vector<T>& v)
:_start(nullptr)
, _finish(nullptr)
, _endofstorage(nullptr)
{
reserve(v.capcity());
const_iterator vit = v.cbegin();
iterator it = begin();
while (vit != v.cend()) {
*it++ = *vit++;
}
}
vector<T>& operator= (vector<T> v) {
swap(v);
return *this;
}
//destroy
~vector() {
delete[] _start;
_finish = nullptr;
_start = nullptr;
_endofstorage = nullptr;
}
// capacity
size_t size() const {
return _finish - _start;
}
size_t capcity() const {
return _endofstorage - _start;
}
void reserve(size_t n) {
if (n > this->capcity()) {
size_t old = size();
T* tmp = new T[n];
if (_start) {
for (int i = 0; i < old; i++) {
tmp[i] = _start[i];
}
}
_start = tmp;
_finish = _start + old;
_endofstorage = _start + n;
}
}
void resize(size_t n, const T& value = T()) {
if (n < capcity()) {
_finish = _start + n;
return;
}
if (n > capcity()) {
reserve(n);
iterator end = _finish;
iterator _end = _start + n;
while (end != _end) {
push_back(value);
end++;
}
}
}
///modify/
void push_back(const T& x) {
insert(end(), x);
}
void pop_back() {
iterator it = _finish - 1;
erase(it);
}
void swap(vector<T>& v) {
_start = v._start;
_finish = v._finish;
_endofstorage = v._endofstorage;
}
iterator insert(iterator pos, const T& x) {
assert(pos <= _finish);
if (size() == capcity()) {
size_t sz = size();
size_t newsz = sz == 0 ? 1 : sz * 2;
reserve(newsz);
pos = _start + sz;
}
iterator end = _finish - 1;
while (end >= pos) {
*(end + 1) = *end;
end--;
}
*pos = x;
_finish++;
return pos;
}
iterator erase(iterator pos) {
iterator begin = pos + 1;
while (begin != _finish) {
*(begin - 1) = *begin;
begin++;
}
_finish--;
return pos;
}
///access///
T& operator[](size_t pos) {
return _start[pos];
}
const T& operator[](size_t pos)const {
return _start[pos];
}
private:
iterator _start;
iterator _finish;
iterator _endofstorage;
};
}
vector的实现
最新推荐文章于 2024-07-25 21:43:46 发布