C++ 模拟实现 vector
程序员文章站
2022-03-23 13:53:20
...
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<list>
#include<assert.h>
using namespace std;
namespace My_Vector
{
template<class T>
class vector
{
public:
typedef T* iterator;
typedef const T* const_iterator;
vector(size_t n = 0, const T& x = T())
:_start(nullptr),_finish(nullptr),_endofstorage(nullptr)
{
resize(n, x);
}
//v1(v)
vector(const vector<T>& v)
:_start(nullptr), _finish(nullptr), _endofstorage(nullptr)
{
reserve(v.capacity());
for (const auto& e : v)
push_back(e);
}
//v1 == v2
vector<T>& operator=(vector<T> v)
{
swap(v);
return *this;
}
iterator begin()
{
return _start;
}
iterator end()
{
return _finish;
}
const_iterator begin() const
{
return _start;
}
const_iterator end() const
{
return _finish;
}
//尾插
void push_back(const T& x)
{
insert(_finish,x);
}
//尾删
void pop_back()
{
erase(_finish - 1);
}
//扩容
void reserve(size_t n)
{
size_t t = 0;
if (n > capacity())
{
t = size();
T *newp = new T[n];
for (int i = 0; i < (int)t; ++i)
{
newp[i] = _start[i];
}
delete[] _start;
_start = newp;
_finish = _start + t; //因为扩容,再调用size()_finish还在旧空间这会导致出错,所以提前算出t
_endofstorage = _start + n;
}
}
//扩容
void resize(size_t n, const T& x = T())
{
if (n > capacity())
{
reserve(n);
while (_finish != _endofstorage)
{
*_finish = x;
++_finish;
}
}
else
{
_finish = _start + n;
}
}
//插入
void insert(iterator pos, const T& x)
{
assert(pos <= _finish);
if (_finish == _endofstorage)
{
size_t tmp = pos - _start;
size_t n = capacity() == 0 ? 2 : capacity() * 2;
reserve(n);
pos = _start + tmp;
}
iterator end = _finish - 1;
while (pos <= end)
{
*(end + 1) = *end;
--end;
}
*pos = x;
++_finish;
}
//删除
void erase(iterator pos)
{
assert(pos < _finish);
iterator cur = pos;
while (cur < _finish)
{
*(cur) = *(cur + 1);
++cur;
}
--_finish;
}
//交换指针
void swap(vector<T>& v)
{
::swap(_start, v._start);
::swap(_finish, v._finish);
::swap(_endofstorage, v._endofstorage);
}
size_t size() const
{
return _finish - _start;
}
size_t capacity() const
{
return _endofstorage - _start;
}
T& operator[](size_t i)
{
return _start[i];
}
//打印
void fun()
{
const_iterator it =begin();
while (it != end())
{
cout << *it << " ";
++it;
}
cout << endl;
}
private:
iterator _start;
iterator _finish;
iterator _endofstorage;
};
}
int main()
{
My_Vector::vector<int> v2(5,1);
My_Vector::vector<int> v1(v2);
My_Vector::vector<int> v3;
v3 = v1;
//v.push_back(1);
/*v.resize(10, 1);
v.resize(1);*/
/*v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
v.push_back(6);
v.push_back(7);*/
//int* it = v.begin();
//int* it = v.end() - 1;
//v.insert(it, 10);
//v.erase(it);
//v.fun();
v1.fun();
v3.fun();
return 0;
}
上一篇: SplayTree实现_简化版
下一篇: Android如何实现时间线效果(下)