当前位置: 首页 > news >正文

reverse_iterator实现

对于实现reverse_iterator,我们可以学栈和队列的实现过程,利用适配器,实现如下;

#pragma oncetemplate<class Iterator,class Ref,class Ptr>
class reverse_Iterator
{
public://构造函数:reverse_Iterator(Iterator it):_it(it){}typedef reverse_Iterator<Iterator, Ref, Ptr> Self;//操作:bool operator!=(const Self& cur){return !(_it == cur._it);}bool operator==(const Self& cur){return _it == cur._it;}Self& operator++(){_it--;return *this;}Self operator++(int){Self tmp(*this);_it--;return tmp;}Self& operator--(){_it++;return *this;}Self operator--(int){Self tmp(*this);_it++;return tmp;}Ref operator*(){//解引用是找前一个:Iterator tmp = _it;return *(--tmp);}Ptr operator&(){//取地址也是找前一个:return &(operator*());}
private:Iterator _it;
};

此时我们将实现的reverse_iterator添加到vector和list上如下:

(注意:vector、list其余部分之前已经实现过了)

vector.h

#pragma once
#include <assert.h>
#include <iostream>
#include <string.h>
#include "reverse_iterator.h"
namespace cx
{//模板类template<class T>class vector{public:typedef T* iterator;typedef const T* const_iterator;typedef reverse_Iterator<iterator, T&, T*> reverse_iterator;typedef reverse_Iterator<const_iterator, const T&, const T*> const_reverse_iterator;//构造函数:vector(){}//传统写法/*vector(const vector<T>& v){_start = new T[v.capacity()];memcpy(_start, v._start, v.size() * sizeof(T));_finish = _start + v.size();_endofstorage = _start + v.capacity();}*///现代写法:vector(const vector<T>& v){reserve(v.capacity());for (const auto e : v){*_finish = e;_finish++;}}vector(size_t n, const T& val = T()){resize(n,val);}/*template <class InputIterator>vector(InputIterator first, InputIterator last){while (first != last){push_back(*first);first++;}}*///析构函数~vector(){if (_start){delete[] _start;_start = _finish = _endofstorage = nullptr;}}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;}reverse_iterator rend(){return _start;}reverse_iterator rbegin(){return _finish;}const_reverse_iterator crend()const{return _start;}const_reverse_iterator crbegin()const{return _finish;}//计算大小size_t size()const {return end() - begin();}size_t capacity()const {return _endofstorage - _start;}//操作:bool empty() const{return _finish == _start;}void swap(vector<T>& v){std::swap(_start, v._start);std::swap(_finish, v._finish);std::swap(_endofstorage, v._endofstorage);}void reserve(size_t n){if (n > capacity()){size_t old = size();T* tmp = new T[n];if (_start){memcpy(tmp, _start, sizeof(T) * old);delete[] _start;}_start = tmp;_finish = _start + old;_endofstorage = _start + n;}}void push_back(const T x){//检查是否扩容if (_finish == _endofstorage){size_t newcapacity = capacity() == 0 ? 4 : 2 * capacity();reserve(newcapacity);}*_finish = x;_finish++;}void pop_back(){assert(size() > 0);_finish--;}T& operator[](size_t pos){assert(pos < size());return _start[pos];}T& operator[] (size_t pos) const{assert(pos < size());return _start[pos];}iterator insert(iterator pos, const T& val){assert(pos <= _finish && pos >= _start);if (_finish == _endofstorage){size_t len = pos - _start;reserve(capacity() == 0 ? 4 : 2 * capacity());pos = _start + len;}//memmove(pos + 1, pos, sizeof(T) * (_finish - pos));iterator end = _finish - 1;while (end >= pos){*(end + 1) = *(end);end--;}*pos = val;_finish++;return pos;}/*void insert(iterator pos, const T& x){//检查assert(pos >= _start);assert(pos <= _finish);if (_finish == _endofstorage){size_t len = pos - _start;reserve(capacity() == 0 ? 4 : 2 * capacity());//注意:pos位置也要改变pos = _start + len;}memmove(pos + 1, pos, sizeof(T) * (_finish - pos));*pos = x;_finish++;}*/iterator erase(iterator pos){assert(pos < _finish && pos >= _start);iterator it = pos + 1;while (it < _finish){*(it - 1) = *it;it++;}_finish--;return pos;}iterator erase(iterator first, iterator last){}void resize(size_t n, T val = T()){if (n > size()){reserve(n);while (_finish < _start + n){*_finish = val;_finish++;}}else{_finish = _start + n;}}T& front(){return *_start;}const T& front() const{*_start;}T& back(){return *_finish;}const T& back() const{return *_finish;}T& at(size_t pos){assert(pos < size());return _start[pos];}const T& at(size_t pos) const{assert(pos < size());return _start[pos];}void assign(size_t n, const T& val){assert(_start == _finish);reserve(n);while (_finish != _endofstorage){*_finish = val;_finish++;}}void clear(){resize(0);}private:iterator _start = nullptr;iterator _finish = nullptr;iterator _endofstorage = nullptr;};
}

list.h:

#pragma once
#include <assert.h>
#include "reverse_iterator.h"
namespace cx
{template <class T>struct ListNode{//构造函数ListNode(const T& x=T()):_next(nullptr),_prev(nullptr),_val(x){}//成员变量:ListNode<T>* _next;ListNode<T>* _prev;T _val;};template <class T,class Ref,class Ptr>//template <class T, class Ref>struct _list_iterator{typedef ListNode<T> Node;typedef _list_iterator<T,Ref, Ptr> self;//typedef _list_iterator<T, Ref> self;//构造函数://_list_iterator()/*iterator(Node* x):_node(x){}*/_list_iterator(Node* x):_node(x){}//不用写析构:原因在于我们的目标不是在这里析构//常见操作:		self& operator++()//前置++{_node = _node->_next;return (*this);}self operator++(int)//后置++{self tmp(*this);_node = _node->_next;return tmp;}self& operator--()//前置--{_node = _node->_prev;return *this;}self operator--(int)//后置--{self tmp(*this);_node = _node->_prev;return tmp;}Ref operator*(){return _node->_val;}bool operator!=(const self& s){return !(_node == s._node);}bool operator==(const self& s){return !(*this != s);}Ptr operator->(){return &_node->_val;}//类成员函数:Node* _node;};//template <class T>//struct _list_const_iterator//{//	typedef ListNode<T> Node;//	typedef _list_const_iterator<T> const_iterator;//	//构造函数://	//_list_iterator()//	/*iterator(Node* x)//		:_node(x)//	{}*///	_list_const_iterator(Node* x)//		:_node(x)//	{}//	//不用写析构:原因在于我们的目标不是在这里析构//	//常见操作:		//	const_iterator& operator++()//前置++//	{//		_node = _node->_next;//		return (*this);//	}//	const_iterator operator++(int)//后置++//	{//		const_iterator tmp(*this);//		_node = _node->_next;//		return tmp;//	}//	const_iterator& operator--()//前置--//	{//		_node = _node->_prev;//		return *this;//	}//	const_iterator& operator--(int)//后置--//	{//		const_iterator tmp(*this);//		_node = _node->_prev;//		return tmp;//	}//	const T& operator*()//	{//		return _node->_val;//	}//	bool operator!=(const const_iterator& s)//	{//		return !(_node == s._node);//	}//	bool operator==(const const_iterator& s)//	{//		return !(*this != s);//	}//	//类成员函数://	Node* _node;//};template <class T>class list{public:typedef ListNode<T> Node;//typedef _list_iterator<T,T&> iterator;typedef _list_iterator<T, T&, T*> iterator;//typedef _list_iterator<T, const T&> const_iterator;typedef _list_iterator<T,const T&,const T*> const_iterator;//typedef reverse_Iterator<iterator, T&, T*> reverse_iterator;typedef reverse_Iterator<const_iterator, const T&, const T*> const_reverse_iterator;//构造函数void empty_list(){_head = new Node;_head->_next = _head;_head->_prev = _head;}list(){empty_list();}//list ( list& x);list(const list<T>& s){empty_list();for (auto e : s)//该类型为:T{push_back(e);}}//list& operator= (const list& lt);//传统写法://list<T>& operator= (list<T>& lt)//{//	if(this != &lt)//	{//		//清除*this中内容//		clear();//		for (T e : lt)//		{//			push_back(e);//		}//	}//	return *this;//}//现代写法:list<T>& operator= (list<T> lt){swap(lt);return *this;}//析构函数:void clear(){//区别析构函数,clear只会删除有效数据,保留虚拟头结点iterator it = begin();while (it != end()){it=erase(it);}}~list(){clear();//删除_head;delete _head;_head = nullptr;}//迭代器:iterator begin()//有效第一个节点{//assert(_head->_next != _head);//如果写上面这句,会出现开始为空链表报错情况return _head->_next;}const_iterator begin() const{return _head->_next;}iterator end(){return _head;}const_iterator end() const{return _head;}reverse_iterator rbegin(){return reverse_iterator(end());}reverse_iterator rend(){return reverse_iterator(begin());}const_reverse_iterator rbegin()const{return const_reverse_iterator(end());}const_reverse_iterator rend()const{return const_reverse_iterator(begin());}//常见操作:iterator erase(iterator pos){//检查pos位置非_head位置assert(pos !=end());//删除的是pos位置Node* current = pos._node;Node* prev = current->_prev;Node* next = current->_next;//删除操作prev->_next = next;next->_prev = prev;delete current;return next;//返回的是pos下一个位置}iterator erase(iterator first, iterator last)//区间左闭右开{assert(first != end());assert(last != end());while (first != last){if (first == end())break;first = erase(first);}return first;}void push_back(const T& val){Node* tmp = new Node(val);Node* tail = _head->_prev;tail->_next = tmp;tmp->_prev = tail;tmp->_next = _head;_head->_prev = tmp;}void swap(list<T>& tmp){std::swap(_head, tmp._head);}iterator insert(iterator pos, const T& x){//insert是指在pos位置前插入Node* current = pos._node;Node* prev = current->_prev;//开空间Node* tmp = new Node(x);tmp->_prev = prev;prev->_next = tmp;tmp->_next = current;current->_prev = tmp;//return iterator(tmp);return tmp;//注意点:单参数的类可以隐式类型转换}//容量相关:bool empty() const{return _head->_next == _head;}size_t size() const{size_t n = 0;Node* tmp = _head->_next;while (tmp!=_head){tmp = tmp->_next;n++;}return n;}void push_front(const T& x){this->insert(begin(), x);}void pop_back(){this->erase(--end());}void pop_front(){erase(begin());}//Element access:T& front(){return _head->_next->_val;}const T& front() const{return _head->_next->_val;}T& back(){return _head->_prev->_val;}const T& back() const{return _head->_prev->_val;}private://虚拟头结点:Node* _head;};
}

这里再给大家一组测试用例:

#include <iostream>using namespace std;
#include "vector.h"
#include "list.h"void test_list()
{cx::list<int> l;l.push_back(1);l.push_back(2);l.push_back(3);l.push_back(4);l.push_back(5);l.push_back(6);cx::list<int>::reverse_iterator it = l.rbegin();while (it != l.rend()){cout << *it << " ";it++;}cout << endl;
}
void test_vector()
{cx::vector<int> l;l.push_back(1);l.push_back(2);l.push_back(3);l.push_back(4);l.push_back(5);l.push_back(6);cx::vector<int>::reverse_iterator it = l.rbegin();while (it != l.rend()){cout << *it << " ";it++;}cout << endl;
}
int main()
{test_list();test_vector();return 0;
}

感谢大家的支持!!!

http://www.lryc.cn/news/320061.html

相关文章:

  • C++:什么情况下函数应该声明为纯虚函数
  • 【全面了解自然语言处理三大特征提取器】RNN(LSTM)、transformer(注意力机制)、CNN
  • 区块链推广海外市场怎么做,CloudNEO服务商免费为您定制个性化营销方案
  • 【S5PV210】 | ARM的指令集合
  • 2024-3-17Go语言入门
  • AJAX-XMLHttpRequest
  • 【GPT-SOVITS-04】SOVITS 模块-鉴别模型解析
  • 论文阅读_时序模型_iTransformer
  • Docker 哲学 - 容器操作 -cp
  • 作品展示ETL
  • python的集合应用
  • 盒子IM开源仿微信聊天程序源码,可以商用
  • 鸿蒙Harmony应用开发—ArkTS声明式开发(基础手势:Web)中篇
  • 静默安装OGG21.3微服务版本FOR ORACLE版本
  • [二分查找]LeetCode2040:两个有序数组的第 K 小乘积
  • 【Godot4.2】颜色完全使用手册
  • Blocks —— 《Objective-C高级编程 iOS与OS X多线程和内存管理》
  • Python零基础---爬虫技术相关
  • 利用 STM32 TIMER 触发 ADC 实现分组转换
  • 2024 年(第 12 届)“泰迪杯”数据挖掘挑战赛——B 题:基于多模态特征融合的图像文本检索完整思路与源代码分享
  • Java12~14 switch语法
  • 小狐狸ChatGPT智能聊天系统源码v2.7.6全开源Vue前后端+后端PHP
  • The Rise and Potential of Large Language Model Based Agents: A Survey
  • 【GPT-SOVITS-06】特征工程-HuBert原理
  • ros小问题之差速轮式机器人轮子不显示(rviz gazebo)
  • 网络安全实训Day5
  • 【Unity入门】详解Unity中的射线与射线检测
  • 实验11-2-5 链表拼接(PTA)
  • Mybatis Plus + Spring 分包配置 ClickHouse 和 Mysql 双数据源
  • 27-3 文件上传漏洞 - 文件类型绕过(后端绕过)