• list的const迭代器的实现


    要实现const迭代器首先要实现普通迭代器,普通迭代器主要是要实现他的解引用、后置加加等操作符,他的底层是指针,但是不是原生指针,是通过用一个类进行封装,通过对类进行传参数来解决问题,先定义链表的结点

    1. template<class T>
    2. struct __list_node
    3. {
    4. __list_node* _prev;
    5. __list_node* _next;
    6. T _val;
    7. __list_node(const T& x)
    8. :_prev(nullptr)
    9. , _next(nullptr)
    10. , _val(x)
    11. {}
    12. __list_node()
    13. :_prev(nullptr)
    14. , _next(nullptr)
    15. {}
    16. };

    接下来是实现list类

    1. template<class T>
    2. class list
    3. {
    4. typedef __list_node Node;
    5. public:
    6. typedef __list_iterator iterator;
    7. typedef __list_iteratorconst T&, const T*> const_iterator;
    8. list()
    9. {
    10. _head = new Node;
    11. _head->_prev = _head;
    12. _head->_next = _head;
    13. }
    14. ~list()
    15. {
    16. clear();
    17. delete _head;
    18. _head = nullptr;
    19. }
    20. iterator begin()
    21. {
    22. return iterator(_head->_next);
    23. }
    24. iterator end()
    25. {
    26. return iterator(_head);
    27. }
    28. const_iterator begin()const
    29. {
    30. return const_iterator(_head->_next);
    31. }
    32. const_iterator end()const
    33. {
    34. return const_iterator(_head);
    35. }
    36. private:
    37. Node* _head;
    38. };

    在这里面我用了三个模板参数去传递,这为之后定义const迭代器埋下了伏笔,接下来实现普通迭代器

    1. template<class T,class Ref,class Ptr>
    2. struct __list_iterator
    3. {
    4. typedef __list_node Node;
    5. typedef __list_iterator Self;
    6. Node* _node;
    7. __list_iterator(Node* node)
    8. :_node(node)
    9. {}
    10. //*it
    11. Ref operator*()
    12. {
    13. return _node->_val;
    14. }
    15. //++it
    16. Self& operator++()
    17. {
    18. _node = _node->_next;
    19. return *this;
    20. }
    21. //it++
    22. Self operator++(int)
    23. {
    24. Self tmp = *this;
    25. //_node = _node->_next;
    26. ++(*this);
    27. return tmp;
    28. }
    29. Self& operator--()
    30. {
    31. _node = _node->_prev;
    32. return *this;
    33. }
    34. Self operator--(int)
    35. {
    36. Self tmp = *this;
    37. //_node = _node->_prev;
    38. --(*this);
    39. return tmp;
    40. }
    41. Ptr operator->()
    42. {
    43. return &_node->_val;
    44. }
    45. bool operator!=(const Self& it)
    46. {
    47. return _node != it._node;
    48. }
    49. };

    在这个迭代器类中,我们定义了三个模板参数,其中第一个是为了传递list存放数据的类型,接下来两个是为了定义接下来的const迭代器在通过list代码中我们可以知道const迭代器传了两个const对象过去,通过传const对象去获得const迭代器,并且通过返回值来是返回的也是const对象,这就是const迭代器的封装类。

  • 相关阅读:
    Flink 源码解读系列 DataStream 带 Watermark 生成的时间戳分配器
    2024中国眼博会·第六届北京国际青少年眼健康产业展览会
    MarkText如何实现图床-解决md上传到csdn图片不显示的问题
    【Web3】DAO相关的基础知识
    vSphere ESXI主机网络分析工具
    用go封装一下封禁功能
    zookeeper源码(04)leader选举流程
    3. 无重复字符的最长子串
    lamda安卓逆向辅助框架
    【Pandas总结】第三节 Pandas 的显示设置(总结所有常用显示设置)
  • 原文地址:https://blog.csdn.net/2301_77312705/article/details/134367789