views:

103

answers:

4

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!

+2  A: 

Nothing much prettier for that, but you can write a templated helper function that will do the same for you internally, and this way at least the call sites will look much cleaner and you'll get lower probability for planting errors through typos.

See the accepted answer to a very similar question and what the solution might look like.

sharptooth
+8  A: 
int* ptrToLastOne = &vec.back(); // precondition: !vec.empty()
Mike Seymour
+4  A: 
int* ptrToLast = &(vec.back()); // Assuming the vector is not empty.
Cătălin Pitiș
+1  A: 

Some more options:

int* ptrToLast = &*vec.rbegin();

or

int* ptrToLast = &*boost::prev(vec.end());
Viktor Sehr