Umur Gurelli Umur Gurelli - 3 months ago 14
C++ Question

Can I get index directly from pointer of vector element in C++?

I have a big vector container that holds around 300.000 object. Also I have pointers to these objects.

Are there any fast way to get index of object in vector with using pointer?

Answer

Since vectors are organized sequentially, you can get an index by subtracting pointer to initial element from the pointer to element in question:

std::vector<MyObject> vect;
MyObject *ptrX = ... // Pointer to element in question
ptrdiff_t index = ptrX - &vect[0];