当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - 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]. Why is it defined in this way. What does prevent vector.begin() to be equal to &vector[0]?

网友答案:

An iterator for vector can be defined as some class. 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.

网友答案:

The iterator returned by vector.begin() technically only lets you get at values via the dereference operator on it. 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.

See: Iterator concept

网友答案:

If we have a vector of Type T

vector<T> v;

then

v.begin() has a different type from &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).

&vector[0] has type 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. In other implementations vector iterator is a class.

To form an iterator that points to the Nth element in a vector, the expression (v.begin() + N) should be used.

To form a pointer to the Nth element in a vector, the expression &v[N] should be used.

These expressions are valid regardless as to how the vendor implements vector iterators. They also hold good for deque and string.

分享给朋友:
您可能感兴趣的文章:
随机阅读: