C++模板实现list,迭代器

来源:互联网 发布:手机淘宝怎么关注 编辑:程序博客网 时间:2024/06/06 18:15

这篇博文主要是帮助去了解STL List与迭代器 算法实现的原理

让我们更明白STL容器的封装 迭代器与智能指针的关系  算法的封装


我们主要是通过链表的实现

下面看一下模板实现紫的链表

节点元素的封装:

#pragma oncetemplate <class T>class Node{public:T data;Node<T>* next;Node();~Node();};


链表的封装:

#pragma once#include "Node.h"#include "Myiterator.h"#include "Node.cpp"template <class T>class ForwardList{private:Node<T>* head;public:ForwardList();~ForwardList();void insert_back(T & data);void insert_front(T & data);void show();Myiterator<T> begin();Myiterator<T> end();void clear();};



迭代器的封装本质就是实现了*  -> ++运算符的智能指针

#pragma once#include "Node.h"template <class T>class Myiterator{private:Node<T>* p;public:Myiterator():p(nullptr){}Myiterator(Node<T>* pnew):p(pnew){}~Myiterator(){}Node<T> operator*(){return *p;}Node<T>* operator->(){return p;}inline void operator++(){p = p->next;}inline void operator++(int){p = p->next;}bool operator !=(Myiterator<T>& myit){return this->p != myit.p;}};



下面就是List的实现代码:

#include "ForwardList.h"template <class T>ForwardList<T>::ForwardList() :head(nullptr){}template <class T>ForwardList<T>::~ForwardList(){clear();}template <class T>void ForwardList<T>::insert_back(T & data){Node<T>* newNode = new Node<T>();newNode->data = data;newNode->next = nullptr;if (this->head == nullptr){this->head = newNode;}else{Node<T>* tmp = this->head;while (tmp->next != nullptr){tmp = tmp->next;}tmp->next = newNode;}}template <class T>void ForwardList<T>::insert_front(T & data){Node<T>* newNode = new Node<T>();newNode->data = data;newNode->next = nullptr;if (this->head == nullptr){this->head = newNode;}else{newNode->next = this->head;this->head = newNode;}}template <class T>void ForwardList<T>::show(){Node<T>* tmp = this->head;while (tmp != nullptr){cout << "data = " << tmp->data << endl;tmp = tmp->next;}}template <class T>Myiterator<T>  ForwardList<T>::begin(){return Myiterator<T>(this->head);}template <class T>Myiterator<T>  ForwardList<T>::end(){Node<T>* tmp = this->head;while (tmp != nullptr){tmp = tmp->next;}return  Myiterator<T>(tmp);}template <class T>void ForwardList<T>::clear(){if (this->head == nullptr){return;}Node<T>* p1 = this->head->next;Node<T>* p2;while (p1 != nullptr){p2 = p1->next;delete p1;p1 = p2;}delete this->head;this->head = nullptr;}



测试代码:

#include <iostream>#include "ForwardList.h"#include "ForwardList.cpp"using namespace std;template<class T,class F>void for_look(T begin,T end,F fun){for (auto ib = begin; ib != end; ib++){fun(*ib);}}void test(){ForwardList<int> mylist;for (int i = 0; i < 5; i++){mylist.insert_back(i);}int i = 100;mylist.insert_front(i);mylist.show();cout << "=========================" << endl;for (auto i : mylist){cout << i.data << endl;}cout << "==========================" << endl;   for_look(mylist.begin(), mylist.end(), [](Node<int> node){cout << node.data << "<---->" << endl; });}void main(){test();cin.get();}


测试结果




是不是跟我们用STL List是一样的呢