I'm wondering if there is prettier syntax for this to get a normal pointer (not an iterator) to the last element in a C++ vector
std::vector<int> vec;
int* ptrToLastOne = &(*(vec.end() - 1)) ;
// the other way I could see was
int* ptrToLastOne2 = &vec[ vec.size()-1 ] ;
But these are both not very nice looking!
If you want to access the last element of your vector use vec. back() , which returns a reference (and not iterator).
std::vector::push_back Adds a new element at the end of the vector, after its current last element.
int* ptrToLastOne = &vec.back(); // precondition: !vec.empty()
int* ptrToLast = &(vec.back()); // Assuming the vector is not empty.
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