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

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

问题描述

我有一个自定义的容器类,我想写入 iterator const_iterator 类。 / p>

我以前从来没有这样做,我找不到合适的方法。关于迭代器创建的指导方针是什么,以及我应该注意什么?



我也希望避免代码重复(我觉得 const_iterator 迭代器共享许多东西;应该是另一个子类)。



>解决方案


  • 选择适合您的容器的迭代器类型:input,output,forward等。

  • 图书馆。例如, std :: iterator with random_access_iterator_tag 。这些基类定义了STL所需的所有类型定义并执行其他工作。

  • 为避免代码重复,是一个模板类,并由值类型,指针类型,引用类型或所有这些(取决于实现)参数化。例如:

      //迭代器类由指针类型参数化
    template< typename PointerType> class MyIterator {
    //迭代器类定义在这里
    };

    typedef MyIterator< int *> iterator_type;
    typedef MyIterator< const int *> const_iterator_type;

    注意 iterator_type const_iterator_type 类型定义:它们是非const和const迭代器的类型。




另请参阅:标准库参考


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 ?

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

Foot note: I'm pretty sure Boost has something to ease this but I can't use it here, for many stupid reasons.

解决方案

  • 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;
    

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

See Also: standard library reference

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆