template<class iterator,class Ref,class Ptr>为reverse_iterator的模板,通过容器类中的typedef传递参数,在reverse_iterator类中重载前置,后置++,--,即使是原生指针也需要重载,因为在test使用迭代器的时候类型已经变成了自定义类型,在容器类中写rbegin(),rend()函数,需要注意返回值需要使迭代器闭环。
#pragma once
#include<iostream>
#include<string>
#include<assert.h>
using namespace std;
namespace yuan{
template<class iterator,class Ref,class Ptr>
struct reverseIterator {
typedef reverseIterator<iterator, Ref, Ptr> self;
iterator _it;
reverseIterator(iterator it) {
_it = it;
}
iterator& operator--() {
_it++;
return _it;
}
iterator operator--(int) {
iterator temp(_it);
_it++;
return temp;
}
iterator& operator++() {
_it--;
return _it;
}
iterator operator++(int) {
iterator temp(_it);
_it--;
return temp;
}
bool operator!=(const self& s) {
if (_it != s._it) {
return true;
}
else {
return false;
}
}
Ref operator*() {
return *_it;
}
Ptr operator->() {
return _it.operator->();
}
};
template<class T>
class vector {
public:
typedef T* iterator;
typedef const T* const_iterator;
typedef reverseIterator<iterator, T&, T*> reverse_iterator;
typedef reverseIterator<const_iterator,const T&,const T*> const_reverse_iterator;
vector(size_t num = 0, const T& t = T()) {
resize(num, t);
}
vector(const vector<T>& v) {
for (const auto& temp : v) {
push_back(temp);
}
}
~vector() {
delete _start;
_start = _finish = _endofstorage = nullptr;
}
iterator begin() {
return _start;
}
iterator end() {
return _finish;
}
const_iterator begin()const {
return _start;
}
const_iterator end()const {
return _finish;
}
reverse_iterator rbegin() {
return _finish - 1;
}
reverse_iterator rend() {
return _start - 1;
}
const_reverse_iterator rbegin() const{
return _finish - 1;
}
const_reverse_iterator rend() const{
return _finish;
}
size_t size() {
return _finish - _start;
}
void reserve(size_t t) {
if (t <= size())
{
return;
}
else
{
T* newRoom = new T[t];
size_t oldsize = size();
memcpy(newRoom, _start, sizeof(T) * size());
delete[] _start;
_start = newRoom;
_finish = _start + oldsize;
_endofstorage = _start + t;
}
}
void resize(size_t numssize,const T& t=T()) {
if (numssize > size()) {
reserve(numssize);
while (_finish < _endofstorage) {
*_finish = t;
_finish++;
}
}
else {
size_t num = size() - numssize;
while (num > 0) {
_finish--;
num--;
}
}
}
void push_back(const T& t = T()) {
reserve(size() + 1);
*_finish = t;
_finish++;
}
iterator erase(iterator pos) {
assert(pos >= _start);
assert(pos < _finish);
for (iterator i = pos; i < _finish-1;i++) {
*i = *(i + 1);
}
_finish--;
return pos;
}
T& operator[](size_t pos) {
return *(_start + pos);
}
const T& operator[](size_t pos) const{
return *(_start + pos);
}
iterator insert(iterator pos,const T& t= T()) {
size_t num = pos - _start;
reserve(size() + 1);
for (iterator i = _finish - 1; i >= _start + num; i--) {
*(i + 1) = *i;
}
*(_start + num) = t;
_finish++;
return _start + num;
}
private:
iterator _start = nullptr;
iterator _finish=nullptr;
iterator _endofstorage = nullptr;
};
}