Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a pointer to last inserted element of a std::vector?

I came up with the following snipped but it looks quite hacky.

vector<int> collection;
collection.push_back(42);
int *pointer = &(*(collection.end()--));

Is there an easy way to get a pointer to the last inserted element?

like image 247
danijar Avatar asked Jun 19 '13 20:06

danijar


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).

How do you pop the last element of a vector in C++?

C++ pop_back() function is used to pop or remove elements from a vector from the back. The value is removed from the vector from the end, and the container size is decreased by 1.

How do you assign a pointer to a vector in C++?

To assign a pointer to 'point to' an instance of an object use pointer = &vector_of_reviews . The & operator gets the address of something, and it's this that you want to assign to the pointer. *pointer = vector_of_reviews dereferences the pointer (obtains the actual object 'pointed to').

What does .back do in C++?

C++ Vector Library - back() Function The C++ function std::vector::back() returns a reference to the last element of the vector. Calling back on empty vector causes undefined behavior.


1 Answers

For std::vector, back() returns a reference to the last element, so &collection.back() is what you need.

In C++17, emplace_back returns a reference to the new element. You could use it instead of push_back:

vector<int> collection;
int *pointer = &collection.emplace_back(42);
like image 76
Casey Avatar answered Sep 23 '22 06:09

Casey