Habalusa
Habalusa

Reputation: 1800

Find index of an element in a vector given a pointer to that element

I have a vector of structs, like so: std::vector<mystruct> elems.

If I then have a mystruct pointer, which I know is pointing to one of the elements of elems, how can I get its index within elems?

Upvotes: 7

Views: 6441

Answers (2)

Steve Jessop
Steve Jessop

Reputation: 279215

ptr - &elems[0];

As of C++03, vector storage is required to be contiguous, and the definition of "contiguous" in the standard is that &v[n] == &v[0] + n;

[Edit: from a fairly theoretical portability point of view, beware that implementations are permitted to define SIZE_MAX and ptrdiff_t such that it's possible to subtract two pointers within the same object with undefined result. You'd hope that no implementation will arrange for that to actually cause problems, but you never know. It's fairly easy for the implementation to avoid - just don't return allocations that big]

Upvotes: 14

CashCow
CashCow

Reputation: 31435

Elements must be stored contiguously. Therefore:

mystruct * elem; // definitely within the vector
mystruct * first = &elems[0];
std::vector<mystruct>::size_type index = elem - first;

technically though should use ptrdiff_t rather than size_type to subtract pointers.

Upvotes: 3

Related Questions