将我们写的 myList 迭代器里面 operator[] 和 operator++ 配合异常再写一遍
实现效果:
myList<int> l;
l << 1 << 3 << 5 << 7 << 9 总共5个数
如果此时,执行了 l[0 ~ 4] 正常,如果执行了 l[5~n] 自动抛出异常
也就是说,我们需要在 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 0
return *this;
}
template <typename T>
T& myList<T>::operator[](int index){
if (index < 0 || index >= count) {
throw std::out_of_range("超出范围"); // 判断并抛出异常
}
Node* p = head->next;
for(int i=0;i<index;i++){
p = p->next;
}
return p->val;
}
template <typename T>
int myList<T>::size(){
return count;
}
int main(int argc,const char** argv){
try {
myList<int> l;
l << 1 << 3 << 5 << 7 << 9; // 插入5个数
myList<int>::iterator it = l.begin();
for (it; it != l.end(); ++it) {
cout << *it << endl;
}
cout << l[5] << endl; // 此行会抛出异常
} catch (const std::out_of_range& e) {
cout <<e.what() << endl;
}
}