W.Joe
W.Joe

Reputation: 345

Iterator return in vector::begin()

I don't quite get what vector::begin() actually returns.

Cplusplus.com tells me that vector::begin() returns the iterator of the vector, which means that for vector<int> v;, it will give 0.

However, when I debug on Visual Studio, the watch table showed me the value of the first element of v. Moreover, the "Type" column denoted that it was a std::_Vector_iterator.

As a consequence, what actually is the output of vector::begin()?

Upvotes: 1

Views: 2953

Answers (2)

R Sahu
R Sahu

Reputation: 206607

Cplusplus.com tells me that vector::begin() returns the iterator of the vector,

That is correct.

which means that for vector<int> v;, it will give 0.

That is an incorrect conclusion from the previous statement. std::vector<T>::begin() returns an iterator that can be used to access the contents of the first element of the object, if it is not empty.

Given,

std::vector<int> v;
auto iter = v.begin();
int b = *iter; // Problem since the vector is empty.

and

std::vector<int> v{1, 3, 10};
auto iter = v.begin();
int b = *iter; // OK. b is the first element of the vector
int c = v[0];  // OK. c is also the first element of the vector.

Perhaps you confusion stems from the fact that the last two lines above evaluate to the same value.

However...

std::vector<T>::iterator is a type in the template std::vector. It is a RandomAccessIterator. You can read more about it, i.e. RandomAccessIterator, at http://en.cppreference.com.

Upvotes: 1

std::vector::begin returns an iterator. An iterator is a generalisation of a pointer — it's a type which can be used to access elements of a container. Each container provides its own iterator type. How exactly iterators are represented is an implementation detail, you as a programmer should only care about their interface (and guarantees they make about stability, validity, etc. See suitable documentation for more info).

Different types of iterators support different operations: some can only be incremeneted (can only move forward), some can also be decremented (move backward); some need to move one step at a time, some can move by multiple elements in one go; etc.

The iterators provided by std::vector are random-access and contiguos, so they function almost exactly the same as pointers do.

For an empty std::vector, calling begin() will give you the exact same iterator as is returned by calling end(). end() always returns a special, past-the-end iterator. That iterator is not dereferenceable (it doesn't point to any element), it just serves as an indicator of the container's end.

Upvotes: 5

Related Questions