思維導圖
?
牛客練習
?練習:
將我們寫的 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[] 函數里面,判斷傳入的下標是否合法,是否在范圍內,如果不合法立刻拋出異常,注意函數內部只負責拋出異常