做壁纸网站好,佛山建网站永网,北京海淀租车公司价格,wordpress如何换域名【C模拟实现】list的模拟实现 目录 【C模拟实现】list的模拟实现list模拟实现的部分代码list模拟实现中的要点const_iterator的实现push_backoperator运算符重载iterator begin()函数 作者#xff1a;爱写代码的刚子 时间#xff1a;2023.9.3 前言#xff1a;本篇博客关于li…【C模拟实现】list的模拟实现 目录 【C模拟实现】list的模拟实现list模拟实现的部分代码list模拟实现中的要点const_iterator的实现push_backoperator运算符重载iterator begin()函数 作者爱写代码的刚子 时间2023.9.3 前言本篇博客关于list的模拟实现和模拟实现中遇到的问题 list模拟实现的部分代码
namespace test
{templateclass Tstruct list_node//默认公有{list_nodeT* _next;list_nodeT* _prev;T _val;list_node(const T val T()):_next(nullptr),_prev(nullptr),_val(val){}};templateclass T,class Ref,class Ptrstruct __list_iterator{typedef list_nodeT Node;typedef __list_iteratorT, Ref, Ptr Self;Node* _node;__list_iterator(Node* nodenullptr):_node(node){}__list_iterator(const Selfl):_node(l._node){}Ref operator*(){return _node-_val;}Ptr operator-(){return _node-_val;}Self operator(){_node_node-_next;return *this;}Self operator(int){Self tmp(_node);return tmp;}Self operator--() {_node_node-_prev;return *this;}Self operator--(int) {Self tmp(*this);_node_node-_prev;return *this;}bool operator!(const Self it) const//引用时一定要注意是否要加上const防止权限放大这里需要加上{return _node!it._node;}bool operator(const Self it) const{return _nodeit._node;}};templateclass Tclass list{typedef list_nodeT Node;public:typedef __list_iteratorT, T ,T* iterator;typedef __list_iteratorT, const T ,const T* const_iterator;iterator begin(){//return _head-_next;return iterator(_head-_next);}iterator end(){//return _head;return iterator(_head);}list(){_headnew Node;_head-_prev_head;_head-_next_head;}~list(){clear();delete _head;_headnullptr;}void clear(){iterator it begin();while(it!end()){iterase(it);}}void push_back(const T x){insert(end(),x);//注意这里是end(),不是end()-1;}void pop_back(){erase(--end());}iterator insert(iterator pos, const T x){Node*newnode new Node(x);pos._node-_prev-_nextnewnode;newnode-_prevpos._node-_prev;newnode-_nextpos._node;pos._node-_prevnewnode;return newnode;}iterator erase(iterator pos){Node*tmppos._node;Node*nexttmp-_next;tmp-_prev-_nexttmp-_next;tmp-_next-_prevtmp-_prev;delete tmp;tmp nullptr;return next;}private:Node* _head;};
}
list模拟实现中的要点
const_iterator的实现
我们选择使用模版参数复用iterator的类设置三个模版参数templateclass T,class Ref,class Ptr并且typedef __list_iteratorT, const T ,const T* const_iterator,具体看代码的实现
push_back
push_back函数中复用了insert函数但是注意的是传入的参数是end(),并不和pop_back函数中一样传入–end();
operator运算符重载
由于迭代器的实现类使用了模版参数所以有两种类const_iterator和iterator所以在使用引用作为传入参数时需注意引用要加const防止使用const_iterator类时权限放大
iterator begin()函数
在此函数中可以使用return _head-_next;编译器会自动使用构造函数构造iterator类 附类的拷贝构造一定要使用引用并考虑是否再加上const。