目录
迭代器
- 迭代器:其实就是一个类中类,通过运算符重载和类中类的对象遍历容器
- 迭代器的分类:
- 正向迭代器:iterator
- begin()
- end()
- 反向迭代器:reverse_iterator
- rbegin()
- rend()
- 常正向迭代器:const_iterator
- cbegin()
- cend()
- 常反向迭代器:const_reverse_iterator
- crbegin()
- crend()
#include<iostream> #include<array> using namespace std; template<class _Ty> struct Node { _Ty data=0; Node<_Ty>* next; Node(_Ty data):data(data),next(nullptr){} Node(_Ty data,Node<_Ty>*next):data(data),next(next){} }; template<class _Ty> class MyList { public: MyList() :frontNode(nullptr), tailNode(nullptr) { curSize = 0; } void push_front(_Ty data){ if (curSize == 0) { frontNode = new Node<_Ty>(data); tailNode =frontNode ; } else { frontNode = new Node<_Ty>(data, frontNode); } curSize++; } void printList() { Node<_Ty>* ptemp=frontNode; while (ptemp != nullptr) { cout << ptemp->data << "\t"; ptemp = ptemp->next; } } void push_back(_Ty data) { if (curSize == 0) { frontNode = new Node<_Ty>(data); tailNode = frontNode; } else { Node<_Ty>* newNode = new Node<_Ty>(data,nullptr); tailNode->next = newNode; tailNode = newNode; } curSize++; } Node<_Ty>* begin() { return frontNode; } Node<_Ty>* end() { return nullptr;//返回end的下一个位置,即nullptr } class iterator { public: bool operator!=(Node<_Ty>* pmove) { return this->pmove != pmove; } iterator operator++(int) { pmove = pmove->next; return iterator(pmove); } _Ty operator*() { return pmove->data; } iterator(Node<_Ty>*pmove=nullptr):pmove(pmove){} iterator(const iterator&object):pmove(object.pmove){} protected: Node<_Ty>* pmove;//迭代器的实质是通过这个数据成员访问链表 }; protected: Node<_Ty>* frontNode; Node<_Ty>* tailNode; int curSize; }; void testIterator() { array<int, 8>Array = { 1,2,3,4,5,6,7,8 }; //正向迭代器 auto iter = Array.begin(); for (; iter != Array.end(); iter++) { cout << *iter << "\t"; } cout