Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why may vector.begin() not equal to &vector[0]?

Tags:

c++

stl

vector

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

like image 817
Ashot Avatar asked Jul 17 '14 16:07

Ashot


People also ask

What does vector begin () do?

vector::begin() function is a bidirectional iterator used to return an iterator pointing to the first element of the container. vector::end() function is a bidirectional iterator used to return an iterator pointing to the last element of the container.

Is vector :: end ()?

The C++ function std::vector::end() returns an iterator which points to past-the-end element in the vector container. The past-the-end element is the theoretical element that would follow the last element in the vector.

How do I print a vector beginning?

To print all elements of a vector, we can use two functions 1) vector::begin() and vector::end() functions. vector::begin() function returns an iterator pointing to the first elements of the vector. vector::end() function returns an iterator point to past-the-end element of the vector.


2 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.

like image 187
Vlad from Moscow Avatar answered Sep 26 '22 14:09

Vlad from Moscow


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

like image 26
Timothy Shields Avatar answered Sep 24 '22 14:09

Timothy Shields