思维导图
牛客练习
练习:
将我们写的 myList 迭代器里面 operator[] 和 operator++ 配合异常再写一遍
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sstream>
#include <vector>
#include <memory>using namespace std;// 该作业要求各位写一个链表
// 所以myList累里面需要一个真正正正的链表template <class T>
class myList{
public:struct Node{T val;Node* next;Node* prev;};class iterator{private:Node* p;public:iterator(Node* p=NULL):p(p){};T& operator*(){return p->val;}bool operator!=(const iterator& r){return p!=r.p;}iterator& operator++(int){p=p->next;return *this;}iterator& operator++(){p=p->next;return *this;}};myList();void push_back(const T& val);myList& operator<<(const T& val);T& operator[](int index);int size();iterator begin();iterator end();
private:Node* head; //真正的链表(链表头头节点)Node* tail; // 链表尾节点int count;
};template <typename T>
typename myList<T>::iterator myList<T>::begin()
{iterator it(head->next);return it;
}template <typename T>
typename myList<T>::iterator myList<T>::end()
{iterator it(tail->next);return it;
}
template <typename T>
myList<T>::myList(){head = new Node;head->next = NULL;head->prev = NULL;tail = head; // 只有头节点的情况下,尾节点即使头节点count = 0;
}template <typename T>
void myList<T>::push_back(const T& val){Node* newnode = new Node;newnode->val = val;newnode->next = NULL;newnode->prev = tail;tail->next = newnode;tail = newnode;count ++;
}template <typename T>
myList<T>& myList<T>::operator<<(const T& val){push_back(val);// return 0return *this;
}template <typename T>
T& myList<T>::operator[](int index){Node* p = head->next;try{for(int i=0;i<index;i++){p = p->next;if(p==head){cout<<"error"<<endl;break;}}throw bad_alloc();}catch(const bad_alloc& e){ cerr<<e.what()<<endl;}return p->val;
}template <typename T>
int myList<T>::size(){return count;
}int main(int argc,const char** argv){myList<int> l;l << 1 << 3 << 5 << 7 << 9;myList<int>::iterator it=l.begin();for(it;it!=l.end();it++){cout<<*it<<"";}cout<<endl;for(auto ele:l){cout<<ele<<"";}cout<<endl;cout<<l[5]<<endl;return 0;
}
实现效果: myList<int> l; l << 1 << 3 << 5 << 7 << 9 总共5个数 如果此时,执行了 l[0 ~ 4] 正常,如果执行了 l[5~n] 自动抛出异常 也就是说,我们需要在 operator[] 函数里面,判断传入的下标是否合法,是否在范围内,如果不合法立刻抛出异常,注意函数内部只负责抛出异常