Reputation: 33
I am learning C++ and the book said the last element in the vector is v[v.size()-1]. What is the logic behind this? Hows size-1 giving me the last element? Would it not give me second from the last element?
Thanks
Upvotes: 0
Views: 1290
Reputation: 12779
the book said the last element in the vector is
v[v.size()-1]
That's true, but only when v.size() > 0
. If the vector is empty, its size is 0, but the value returned by std::vector::size()
is of type std::vector::size_type
which is an unsigned integer type (usually std::size_t
), so that the result "wraps around" becoming an "unexpected" huge value (the maximum representable value of size_type
, actually).
You can also use v.back()
, where std::vector::back()
"returns reference to the last element in the container. Calling back
on an empty container causes undefined behavior."
What is the logic behind this?
In C++, vector (and array) indeces start from 0, so that v[0]
would return a reference to the first element, if present. In general accessing a nonexistent element through operator[]
is undefined behavior.
To picture it, let's consider a vector of size 5.
v[0] v[1] v[2] v[3] v[4] +-----+-----+-----+-----+-----+ - - | 1 | 2 | 3 | 4 | 5 | | +-----+-----+-----+-----+-----+ - - ^ ^ v.begin() v.end()
Note that the v.end()
iterator points exactly at v.begin() + v.size()
and that the last accessible element is the one before that.
Upvotes: 5
Reputation: 8490
Do you undestand memory position? All vectors are index starting at 0, not at one. So if your vectors has 10 elements, the last is at the position 9.
This occurs because C language has arrays. Arrays are pointers to a position memory, so the position 0 means the start of the array, if you get the position 1 you add a value to the pointer.
If you have int[] arr = ...
arr[0]
has the same value of arr
arr[1]
can be replaced by arr + sizeof(int)
Upvotes: 0
Reputation: 182827
If there's one element, it's element zero. If there are two elements, they are zero and one. So the last element is the element with an index one less than the number of elements.
It may help intuitively to think as an element's index as its distance from the first element.
Upvotes: 2