Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

stl

stdvector

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.

like image 953
lezebulon Avatar asked Nov 16 '11 21:11

lezebulon


1 Answers

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.

like image 171
K-ballo Avatar answered Sep 28 '22 02:09

K-ballo