danijar danijar - 18 days ago 7
C++ Question

Get index of object inserted into a vector

How can I get the position where my object was actually inserted?

#include <vector>
using namespace std;

vector<SomeClass> list;
SomeClass object;
list.push_back(object);

list[...].method(); // I do not have the key


Unfortunately
push_back
does not return anything since its return type is
void
.

NPE NPE
Answer

If v is your vector, the following will give you the position (that is, the index):

v.push_back(object);
size_t pos = v.size() - 1;

Or you can look at the size() before calling push_back(). Then you won't need to subtract one.