[英]Why may vector.begin() not equal to &vector[0]?
Here http://www.parashift.com/c++-faq/vector-is-contiguous.html is stated that vector.begin()
may not be equal to &vector[0]
. 这里指出http://www.parashift.com/c++-faq/vector-is-contiguous.html表示
vector.begin()
可能不等于&vector[0]
。 Why is it defined in this way. 为什么以这种方式定义它。 What does prevent
vector.begin()
to be equal to &vector[0]
? 什么阻止
vector.begin()
等于&vector[0]
?
An iterator for vector can be defined as some class. vector的迭代器可以定义为某个类。 As member function returns the iterator then it is not necessary that it is a raw pointer to the first element of the array.
当成员函数返回迭代器时,它不必是指向数组的第一个元素的原始指针。 It can be an object of that class.
它可以是该类的一个对象。 It is only required that the iterator would have defined
operator *
that will return reference to the first element of a vector provided that the vector is not empty. 只需要迭代器定义
operator *
,它将返回对向量的第一个元素的引用,前提是向量不为空。
The iterator returned by vector.begin()
technically only lets you get at values via the dereference operator on it. vector.begin()
返回的迭代器在技术上只允许你通过dereference运算符获取值。 That dereference operator could be doing all sorts of things inside. 那个解引用操作符可以在里面做各种各样的事情。 Most implementations simply store a pointer to a
T
- or are a pointer to a T
- and then simply dereference it in their dereference operator, but that's not a requirement of the iterator concept. 大多数实现只是存储一个指向
T
的指针 - 或者是指向T
的指针 - 然后在它们的解引用操作符中简单地取消引用它,但这不是迭代器概念的要求。
See: Iterator
concept 请参阅:
Iterator
概念
If we have a vector of Type T 如果我们有一个T型向量
vector<T> v;
then 然后
v.begin()
has a different type from &v[0]
v.begin()
与&v[0]
类型不同
v.begin()
has type vector<T>::iterator
(if the vector is non-const) or vector<T>::const_iterator
(if the vector is const). v.begin()
具有类型vector<T>::iterator
(如果向量是非const)或vector<T>::const_iterator
(如果向量是const)。
&vector[0]
has type T *
&vector[0]
类型为T *
Now in some implementations, a vector iterator is implemented as a pointer to T. So some programmers have assumed that vector iterators are synonymous with pointer to T. This is not backed by the standard. 现在在一些实现中,向量迭代器被实现为指向T的指针。因此一些程序员假设向量迭代器与指向T的指针同义。这不受标准的支持。 In other implementations vector iterator is a class.
在其他实现中,vector迭代器是一个类。
To form an iterator that points to the Nth element in a vector, the expression (v.begin() + N)
should be used. 要形成指向向量中第N个元素的迭代器,应使用表达式
(v.begin() + N)
。
To form a pointer to the Nth element in a vector, the expression &v[N]
should be used. 要形成指向向量中第N个元素的指针,应使用表达式
&v[N]
。
These expressions are valid regardless as to how the vendor implements vector iterators. 无论供应商如何实现向量迭代器,这些表达式都是有效的。 They also hold good for deque and string.
它们也适用于双端和弦乐。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.