tower120
tower120

Reputation: 5255

Converting std::vector element pointer to index

Can I convert std::vector element pointer to index with this?

http://coliru.stacked-crooked.com/a/cedf3d849539e001

template<class T>
std::size_t get_index(std::vector<T>& vec, T* ptr){
    const std::size_t i = ptr - &(*vec.begin());
    return i;
}

If elements in vector is guaranteed to be contiguous, then I think we can do such pointer arithmetic... Or no?

Upvotes: 0

Views: 483

Answers (2)

user1143634
user1143634

Reputation:

Vector elements are stored contiguously, yes. You can also use std::vector<T>::data() instead of &*std::vector<T>::begin().

You can read more at: http://en.cppreference.com/w/cpp/container/vector

PS: There is already a question about this - Are std::vector elements guaranteed to be contiguous?

Upvotes: 2

eerorika
eerorika

Reputation: 238351

If elements in vector is guaranteed to be contiguous, then I think we can do such pointer arithmetic...

Elements in vector are guaranteed to be contiguous, and you can use such pointer arithmetic indeed.

However, there is a caveat: addressof operator can be overloaded to return something other than the address. If you cannot guarantee that it won't be overloaded, use std::addressof instead.

Or simply use std::vector::data as shown by Ivan.

Upvotes: 2

Related Questions