Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get index directly from pointer of vector element in C++?

I have a big vector container that holds around 300.000 object. Also I have pointers to these objects.

Are there any fast way to get index of object in vector with using pointer?

like image 758
Umur Gurelli Avatar asked Aug 25 '16 09:08

Umur Gurelli


2 Answers

Since vectors are organized sequentially, you can get an index by subtracting pointer to initial element from the pointer to element in question:

std::vector<MyObject> vect;
MyObject *ptrX = ... // Pointer to element in question
ptrdiff_t index = ptrX - &vect[0];
like image 92
Sergey Kalinichenko Avatar answered Sep 30 '22 00:09

Sergey Kalinichenko


Iterator header should be useful in that case.

Let's assume you have something like:

using Vector = std::vector<Foo>;
using Iterator = Vector::iterator;

Vector big_vector;

And now your have an iterator to an object:

Iterator p_obj = get_Theobj(big_vector);

The the index could be easily get with distance:

auto index = std::distance(big_vector.begin(), p_obj);
// Note: index's type is a `difference_type` aka ptrdiff_t (usually signed integer).

The powerful of using that approach is the versatility. Indeed, it works with "C-like vector", std::array, std::list, as well.

like image 33
BiagioF Avatar answered Sep 30 '22 01:09

BiagioF