I am a new C++ learner, and I read a code block about C++ STL accessing the last element from a vector.
Why does the code at line 6, 7, and 8 need to subtract 1 to be equal to that at line 5?
1. std::vector<int> v;
2. v.push_back(999);
3. //fill up the vector
4. //...
5. int j = v.back();
6. int j = v.[size-1]
7. int j = v.at(v.size()-1)
8. int j = *(v.end()-1)
Here's an illustration of which is which
v: [ 1 | 2 | 3 | 4 | ... | 999 ]
🡑 🡑 🡑
front() back() end()
🡑
begin()
where front()
and back()
return a (const) reference to the first and last element respectively, and end()
returns an iterator (sort of a pointer) to one beyond the last element of vector. begin()
returns an iterator to the first element of a vector.
These are also explained at std::vector
front
access the first elementback
access the last elementend
/cend
returns an iterator to the endbegin
/cbegin
returns an iterator to the beginning
Subtracting one from size is because an index in C or C++ starts at zero, and not one as usually. This means, in order to access the first element of an array, or in this case of a vector, you say
v[0]
and not
v[1]
Equally for the last (nth) element, you wouldn't take size
or n
of an array (a vector), but rather one less, e.g.
v[size() - 1]
or
v[n - 1]
5. int j = v.back();
std::vector::back
is defined to return the last element in the vector. This is straight forward.
7. int j = v.[size-1]
Indices are 0 based in c++. If a sequential container has N elements, the valid indices are between 0 and N-1 inclusively. The last element is therefor N-1, or size()-1
.
8. int j = *(v.end()-1)
std::vector::end
returns an iterators to one-past-the-end of the container. The element just before is then the last element in the vector.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With