10

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?

danijar
  • 32,406
  • 45
  • 166
  • 297

1 Answers1

22

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);
Casey
  • 41,449
  • 7
  • 95
  • 125
  • Thanks a lot. Moreover, if the vector holds `std::pair`s, do you know how to get a pointer to the second element of the last pair? – danijar Jun 19 '13 at 20:15
  • 6
    `&(collection.back().second)` – Peter Wood Jun 19 '13 at 20:18
  • @PeterWood Gives me a bad function exception if I bind that pointer to a function. Could it have to do with the pointer and thus with the question? Otherwise I would ask another one to not mix up topics. – danijar Jun 19 '13 at 20:25
  • @danijar If you're sure you have the parentheses in the right place, then the problem is likely something else. New question. – Casey Jun 19 '13 at 20:27