Get the index of a std::vector element given its address

Since you know the element is within the vector, and vector guarantees that its storage is contiguous, you could do:

index = element_pointer - vector.data();

or

index = element_pointer - &vector[0];

Note that technically the contiguous guarantee was introduced in C++03, but I haven't heard of a C++98 implementation that doesn't happen to follow it.


distance( xxx.begin(), theIterator);

The above will only work for a vector::iterator. If you only have a raw pointer to an element, you must use it this way:

distance(&v[0], theElementPtr);

Tags:

C++

Stl

Stdvector