C++ 常量和非常量容器的自定义迭代器
C++ Custom iterator for both const and non const container
我想为树实现一个自定义树类型(类似stl)和一个自定义迭代器。正如我对标准库的理解,任何容器只有 4 种类型的迭代器(常量/非常量、反向/非反向的组合),并且 const 是指它所持有的数据,而不是容器本身。
出于某种原因,在我的迭代器类中,我具有树类型的属性(我需要返回对它的 const 正确引用),这迫使我在用户创建 const 容器时使用不同的类型。
template <typename T> class tree;
template <typename T> class node;
template <typename T, typename Tree = tree<T>, typename Node = node<T>>
class iterator_base : public std::iterator<std::bidirectional_iterator_tag, T> {
protected:
Tree *tree;
Node *current_node;
public:
Tree& get_tree() const {
return *tree;
}
//...
};
是否可以对const tree
和tree
使用相同的迭代器类型?
基本上你应该
能够使用以下版本的迭代器:
typedef iterator_base<T, tree<T>, node<T> > iterator;
//either use T or const T for const_iterator (depends on your definition
//of const correctness in this case.
typedef iterator_base<T, const tree<T>, const node<T> > const_iterator;
唯一缺少的是从迭代器到const_iterator的隐式转换(可以使用template_if或通过子类化并仅指定这些成员来完成。如果使用const T
则可能需要其他帮助程序函数将tree<T>
转换为const tree<const T>
)
注意:此方法仅在迭代器上没有直接修改树/节点的特殊非常量成员时才有效(此类方法将/不应该在const_iterator上工作)
相关文章:
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- C++自定义比较函数
- 如何比较自定义类的std::变体
- std::设置自定义比较器
- 如何正确实现和访问运算符的各种自定义枚举器
- flutter:即使shouldRepaint()返回true,自定义画家也不会重新绘制
- 自定义先决条件对移动分配运算符有效吗
- 使用VS Code和CMake Tools运行自定义命令
- 如何创建从Maya(或类似程序)到虚幻引擎的自定义数据导出插件
- C++ 确保子类为常量提供自定义值
- 自定义引用包装器的常量正确性
- 可视的 GNU C++不能创建常量自定义类实例的向量
- 自定义字符串类中的常量字符*差异
- 自定义类的const实例化是否也会使类中的*everything*变为常量
- 从自定义 printf 函数返回一个常量字符*
- 自定义迭代器和自定义常量迭代器之间的转换
- 引用std::basic_string特化string与自定义分配器作为std::string的常量对象,没有开销
- 按常量id排序自定义类型的向量
- C++ 常量和非常量容器的自定义迭代器