Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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?

like image 302
Habalusa Avatar asked Mar 03 '11 10:03

Habalusa


People also ask

How do you find the index element of a vector?

Access an element in vector using vector::at() reference at(size_type n); reference at(size_type n); It returns the reference of element at index n in vector. If index n is out of range i.e. greater then size of vector then it will throw out_of_range exception.

How do you find the index of an element in a vector in R?

Use the match() Function to Find the Index of an Element in R. The match() function is very similar to the which() function. It returns a vector with the first index (if the element is at more than one position as in our case) of the element and is considered faster than the which() function.


1 Answers

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]

like image 91
Steve Jessop Avatar answered Oct 03 '22 06:10

Steve Jessop