Question

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?

Was it helpful?

Solution

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top