[英]How to define the type of a member of an iterator class to work with STL container methods?
I wish to define an iterator class over a vector, and how can its private member p
match the return type of std::vector::begin()? 我希望在向量上定义一个迭代器类,它的私有成员
p
如何匹配std :: vector :: begin()的返回类型?
class A{
struct element{
...
}
class e_iterator {
e_iterator() : p()
...
private:
element* p;
};
e_iterator e_begin() const{
e_iterator Iter;
Iter.p = e_.begin(); // error
return Iter;
}
std::vector<element> e_;
} I receive an error with element* p
: 我收到
element* p
的错误:
error: cannot convert 'std::vector<element, std::allocator<element>>::const_iterator' to 'element*' in assignment
With what you've given, the most I can suggest is changing p
to: 根据你给出的,我建议的最多是将
p
改为:
std::vector<element>::const_iterator p;
The simple fact is that a std::vector
iterator is not a pointer (probably). 简单的事实是
std::vector
迭代器不是指针(可能)。 It is an unspecified type that behaves like a pointer - it meets the requirements of a Random Access Iterator. 它是一种未指定的类型,其行为类似于指针 - 它满足随机访问迭代器的要求。
When you call begin()
on a non- const
container, you get an iterator
type. 在非
const
容器上调用begin()
时,会得到iterator
类型。 When you call it on a const
iterator, you get a const_iterator
type. 在
const
迭代器上调用它时,会得到一个const_iterator
类型。 Since your a_begin
member function is marked const
and e_
appears to be a std::vector<element>
member of your class, e_
is transitively const
, so calling begin()
on it will also get you a const_iterator
. 由于你的
a_begin
成员函数被标记为const
而e_
似乎是你的类的std::vector<element>
成员,所以e_
是传递const
,所以在它上面调用begin()
也会得到一个const_iterator
。
But it's quite hard to tell exactly what you're trying to do here and whether this is the right way to go about it. 但是很难准确地说出你在这里想做什么,以及这是否是正确的方法。
Either change element* p
to const element* p
in your iterator class or remove the const qualifier from your e_begin() method. 在迭代器类中将
element* p
更改为const element* p
或从e_begin()方法中删除const限定符。 Or provide both const/non-const iterator. 或者提供const / non-const迭代器。 I also suggest to initialize the pointer in the iterator constructor:
我还建议初始化迭代器构造函数中的指针:
template <bool isconst>
class e_iterator_ {
public:
typedef std::conditional<isconst, const element*, element*>::type elementptr;
e_iterator_(elementptr e) : p(e)
...
private:
elementptr p;
};
typedef e_iterator_<true> const_e_iterator;
typedef e_iterator_<false> e_iterator;
Then you could use the data()
member method of std::vector to directly access the underlying array of the vector. 然后你可以使用std :: vector的
data()
成员方法直接访问向量的底层数组。
e_iterator e_begin() const{
const_e_iterator Iter(e_.data());
return Iter;
}
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.