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.
Let’s say I have a std::vector and I get by some means the address
Share
Since you know the element is within the vector, and vector guarantees that its storage is contiguous, you could do:
or
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.