`const_iterator`真的需要与`iterator`不同吗? [英] Does `const_iterator` really need to be a different class than `iterator`?
问题描述
假设我定义了某种容器 A
:
Let say I define some kind of container A
:
struct A
{
iterator begin(){ return iterator(this,0); }
const iterator cbegin() const { return iterator(this, last());}
//...
};
假设现在我要声明迭代器
(A的一部分):
Suppose now I want to declare the iterator
(part of A):
struct A::iterator
{
iterator ( A* ptr, size_t idx){};
//...
};
我会用的是:
const A a;
A::iterator it = a.cbegin();
这不起作用,因为指针传递给 iterator的构造函数
是非常量的。
That does not work because the pointer passed to the constructor of iterator
is non-const.
理想的解决方案就像返回const对象的特定构造函数:
The ideal solution would be something like a specific constructor that return a const object:
const A::iterator( const StringUtfInterface *p, size_t s); //Not valid
这显然在C ++中无效。我想知道这个问题的解决方法是什么?
This is (obviously) not valid in C++. I wonder what is the approach to this problem?
我真的需要声明/定义一个新的const_iterator类吗? const
关键字是不够的?
Do I really need to declare/define a new const_iterator class? const
keyword is not enough?
相关问题(但不是相同):
Related questions (but not the same):
- Why does C++ not have a const constructor?
- Get iterator for const reference
推荐答案
const
关键字是不够的?
实际上, const
关键字太多了:它强迫你写
Actually, const
keyword is too much: it forces you to write
const A::iterator it = a.cbegin();
这会阻止你使用 ++它
稍后。
您需要提供两个单独的类,但这并不意味着您必须两次编写代码。您可以构造迭代器的实现,使得执行所有工作的公共类嵌入到常量和非常量迭代器实现中,这将实现嵌入式实现的相关方法给调用者。
You need to provide two separate classes, but it does not mean that you have to write the code twice. You can structure an implementation of your iterator in such a way that a common class that does all the work is embedded in both constant and non-constant iterator implementations, which expose the relevant methods of the embedded implementation to the callers.
这篇关于`const_iterator`真的需要与`iterator`不同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!