Prettier syntax for "pointer to last element", std::vector?

bobobobo picture bobobobo · Sep 6, 2010 · Viewed 15.2k times · Source

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!

Answer

Mike Seymour picture Mike Seymour · Sep 6, 2010
int* ptrToLastOne = &vec.back(); // precondition: !vec.empty()