How to correctly implement custom iterators and const_iterators?(如何正确实现自定义迭代器和 const_iterators?)
问题描述
我有一个自定义容器类,我想为其编写 iterator 和 const_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_iterator 和 iterator 共享很多东西;一个应该继承另一个吗?).
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::iterator和random_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::iteratorwithrandom_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_type和const_iterator_type类型定义:它们是非常量和 const 迭代器的类型.Notice
iterator_typeandconst_iterator_typetype definitions: they are types for your non-const and const iterators.另请参阅:标准库参考
std::iterator自 C++17 起已弃用.查看相关讨论此处.std::iteratoris deprecated since C++17. See a relating discussion here.这篇关于如何正确实现自定义迭代器和 const_iterators?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何正确实现自定义迭代器和 const_iterators?
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
