#pragma once
#include<assert.h>
namespace sxh_vector
{
template<typename T>
class vector
{
public:
typedef T* iterator;
typedef const T* const_iterator;
vector() :_start(nullptr), _finish(nullptr), _endofstorage(nullptr) {}
vector(size_t n, const T& val = T()) :_start(new T[n]), _finish(_start), _endofstorage(_start + n)
{
for (int i = 0; i < n; ++i)
{
_start[i] = val;
}
_finish = _start + n;
}
vector(const vector<T>& vt):_start(nullptr),_finish(nullptr),_endofstorage(nullptr)
{
for (const auto& e : vt)
this->push_back(e);
}
iterator begin()
{
return _start;
}
const_iterator begin()const
{
return _start;
}
iterator end()
{
return _finish;
}
const_iterator end()const
{
return _finish;
}
void reserve(size_t newcapacity)
{
if (newcapacity > capacity())
{
T* temp = new T[newcapacity];
size_t oldsize = size();
if (_start)
{
//memcpy为浅拷贝,不宜使用
//memcpy(temp,_start,oldsize);
for (size_t i = 0; i < oldsize; ++i)
{
temp[i] = _start[i];
}
delete[] _start;
}
_start = temp;
_endofstorage = _start + newcapacity;
_finish = _start + oldsize;
}
}
void push_back(const T& val)
{
/*if (_finish == _endofstorage)
{
size_t newcapacity = capacity() == 0 ? 2 : capacity() * 2;
reserve(newcapacity);
}
*_finish = val;
++_finish;*/
insert(_finish, val);
}
void pop_back()
{
erase(_finish-1);
}
void swap(vector<T>& vt)
{
std::swap(this->_start,vt._start);
std::swap(this->_finish, vt._finish);
std::swap(this->_endofstorage, vt._endofstorage);
}
iterator erase(iterator pos)
{
assert(pos < _finish);
iterator postion = pos;
while (pos<_finish)
{
*pos = *(pos + 1);
pos++;
}
--_finish;
return postion;
}
void insert(iterator pos, const T& val)
{
assert(pos <= _finish);
if (_finish == _endofstorage)
{
size_t n = pos - _start;
size_t newcapacity = capacity() == 0 ? 2 : capacity() * 2;
reserve(newcapacity);
//扩容后迭代器会失效,需重新获取位置
pos = _start+n;
}
iterator end = _finish - 1;
while (end >= pos)
{
*(end + 1) = *end;
--end;
}
*pos = val;
++_finish;
}
void resize(size_t newsize,const T& val = T())
{
//helloworld
//resize(3)
if (newsize <= size())
{
_finish = _start + newsize;
}
//resize(30)
else
{
if (newsize > capacity())
{
reserve(newsize);
}
while (_finish < _start+newsize)
{
*_finish = val;
++_finish;
}
}
}
size_t size()
{
return _finish - _start;
}
size_t capacity()
{
return _endofstorage - _start;
}
T& operator[](const size_t& i)
{
return _start[i];
}
const T& operator[](const size_t& i)const
{
return _start[i];
}
vector<T>& operator=(vector<T> vt)
{
this->swap(vt);
return *this;
}
private:
iterator _start;
iterator _finish;
iterator _endofstorage;
};
}
C++ vector容器模拟实现(初阶)
于 2023-12-29 21:59:15 首次发布
本文详细介绍了C++标准库中的vector模板类,包括构造方法、迭代器操作、内存管理(reserve)、元素添加和删除(push_back,pop_back,insert,erase)以及resize函数的用法。
摘要由CSDN通过智能技术生成