Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 435
bobobobo Avatar asked Sep 06 '10 13:09

bobobobo


People also ask

How do you get the last element of std::vector?

If you want to access the last element of your vector use vec. back() , which returns a reference (and not iterator).

What method adds an item to the end of a vector C++?

std::vector::push_back Adds a new element at the end of the vector, after its current last element.


2 Answers

int* ptrToLastOne = &vec.back(); // precondition: !vec.empty()
like image 185
Mike Seymour Avatar answered Sep 18 '22 07:09

Mike Seymour


int* ptrToLast = &(vec.back()); // Assuming the vector is not empty.
like image 38
Cătălin Pitiș Avatar answered Sep 18 '22 07:09

Cătălin Pitiș