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]
?

- 10,807
- 14
- 66
- 117
-
3`vector.begin()` returns a `vector::iterator` which is a container. So it is not simply a reference to the first element. – Cory Kramer Jul 17 '14 at 16:20
-
12In addition to reasons mentioned in the answers, `vector.begin()` is well-defined even when the `vector` is empty. `&vector[0]` is not. – Pradhan Jul 17 '14 at 16:36
-
1@Cyber: `vector` is a container, `vector::iterator` is a class. – Mooing Duck Jul 17 '14 at 18:11
3 Answers
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.

- 301,070
- 26
- 186
- 335
-
-
@Aaron McDaid Yes we can. *v.begin returns reference to front. – Vlad from Moscow Jul 17 '14 at 22:19
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

- 75,459
- 18
- 120
- 173
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.

- 756
- 5
- 11
-
And may even be a different class in "debug" vs "release" builds. A compiler vendor could provide some sort of diagnostic iterator for debug builds which will assert or exception or something on invalid iterator usages. – Andre Kostur Jul 17 '14 at 19:56
-
note: `&v[N]` is not valid when `N == v.size()`, however `v.begin() + N` is valid. – M.M Jul 17 '14 at 21:41