Reputation: 1800
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
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
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