简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM