danijar danijar - 5 days ago 6
C++ Question

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?

Answer

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);
Comments