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

danijar picture danijar · Jun 19, 2013 · Viewed 9.1k times · Source

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

Casey picture Casey · Jun 19, 2013

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