Search code examples
c++stlstdvector

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


Let's say I have a std::vector and I get by some means the address of the n-th element. Is there a simple way (faster than iterating through the vector) to get the index at which the element appears, given the base address of my std::vector? Let's assume I'm sure the element is in the vector.


Solution

  • 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.