Prettier syntax for “pointer to last element”, std

2020-08-09 10:06发布

问题:

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!

回答1:

int* ptrToLastOne = &vec.back(); // precondition: !vec.empty()


回答2:

int* ptrToLast = &(vec.back()); // Assuming the vector is not empty.


回答3:

Some more options:

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

or

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


回答4:

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.