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?
If you want to access the last element of your vector use vec. back() , which returns a reference (and not iterator).
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.
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').
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With