Umur Gurelli Umur Gurelli -4 years ago 213
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 Source

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];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download