如何正确实现自定义迭代器和 const_iterators?

How to correctly implement custom iterators and const_iterators?(如何正确实现自定义迭代器和 const_iterators?)

本文介绍了如何正确实现自定义迭代器和 const_iterators?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义容器类,我想为其编写 iteratorconst_iterator 类.

I have a custom container class for which I'd like to write the iterator and const_iterator classes.

我以前从未这样做过,也没有找到合适的方法.关于迭代器创建的准则是什么?我应该注意什么?

I never did this before and I failed to find an appropriate how-to. What are the guidelines regarding iterator creation, and what should I be aware of ?

我还想避免代码重复(我觉得 const_iteratoriterator 共享很多东西;一个应该继承另一个吗?).

I'd also like to avoid code duplication (I feel that const_iterator and iterator share many things; should one subclass the other ?).

脚注:我很确定 Boost 可以缓解这种情况,但由于许多愚蠢的原因,我不能在这里使用它.

推荐答案

  • 选择适合您容器的迭代器类型:输入、输出、转发等.
  • 使用标准库中的基迭代器类.例如,std::iteratorrandom_access_iterator_tag.这些基类定义了 STL 所需的所有类型定义并完成其他工作.
  • 为避免代码重复,迭代器类应该是一个模板类,并通过值类型"、指针类型"、引用类型"或全部参数化(取决于实现).例如:

    • Choose type of iterator which fits your container: input, output, forward etc.
    • Use base iterator classes from standard library. For example, std::iterator with random_access_iterator_tag.These base classes define all type definitions required by STL and do other work.
    • To avoid code duplication iterator class should be a template class and be parametrized by "value type", "pointer type", "reference type" or all of them (depends on implementation). For example:

      // iterator class is parametrized by pointer type
      template <typename PointerType> class MyIterator {
          // iterator class definition goes here
      };
      
      typedef MyIterator<int*> iterator_type;
      typedef MyIterator<const int*> const_iterator_type;
      

      注意 iterator_typeconst_iterator_type 类型定义:它们是非常量和 const 迭代器的类型.

      Notice iterator_type and const_iterator_type type definitions: they are types for your non-const and const iterators.

      另请参阅:标准库参考

      std::iterator 自 C++17 起已弃用.查看相关讨论此处.

      std::iterator is deprecated since C++17. See a relating discussion here.

      这篇关于如何正确实现自定义迭代器和 const_iterators?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何正确实现自定义迭代器和 const_iterators?

基础教程推荐