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?
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];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With