2

I made a vector v which is [-5,-3]. I assigned an iterator iti to its beginning and then assigned another iterator itj as iti+1. Since my vector only has 2 elements, I would think that itj is recognized as the end of the vector or v.end(). But it is not.

Any ideas why that might be happening?

vector<int>v;
v.push_back(-5);
v.push_back(-3);

vector<int>::iterator iti, itj;
iti = v.begin();
itj = iti + 1;

if(itj==v.end())
    cout << "1";
else
    cout << "2";

Why does this print out '2' and not '1'?

1
  • 10
    .end() is not an iterator to the last element, but an iterator to "one past the last element". So iti + 2 == v.end() is true. Commented May 22, 2020 at 14:19

2 Answers 2

8

end is an iterator to the (non-existing) element after the last element. iti + 2 would equal end because the vector has 2 elements. Generally, for a vector of size N: begin + N equals end.

Sign up to request clarification or add additional context in comments.

Comments

2

The definition of vector:: end() is made in such a way that it returns the iterator which points to the (imaginary) element next to the last element.

Now, this might appear stupid initially, but is actually very useful, because, generally you use an iterator to iterate through a vector. And that is usually done using a for loop. So people do

for (vector<int>:: iterator i = v.begin();i!=v.end();i++)

which iterates over the whole vector.

Now I am not saying that we cannot achieve this if end returns an iterator to the last element. It is of course possible to do it, if we change the structure of our loop a little.

So, let us assume for a moment that end does return an iterator pointing to the last element. Now try to write a piece of code to iterate over the whole vector, say to print it. You will understand why the designers chose this kind of a convention. Remember that you cannot compare two iterators with <= like you do with normal integer indices.

BTW, it is the same convention for all STL containers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.