[英]Converting std::vector element pointer to index
Can I convert std::vector
element pointer to index with this? 我可以将
std::vector
元素指针转换为此索引吗?
http://coliru.stacked-crooked.com/a/cedf3d849539e001 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? 如果保证向量中的元素是连续的,那么我认为我们可以做这样的指针算术……还是不?
Vector elements are stored contiguously, yes. 向量元素是连续存储的,是的。 You can also use
std::vector<T>::data()
instead of &*std::vector<T>::begin()
. 您也可以使用
std::vector<T>::data()
代替&*std::vector<T>::begin()
。
You can read more at: http://en.cppreference.com/w/cpp/container/vector 您可以在以下网址了解更多信息: http : //en.cppreference.com/w/cpp/container/vector
PS: There is already a question about this - Are std::vector elements guaranteed to be contiguous? PS:对此已经存在一个问题-std :: vector元素是否保证是连续的?
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. 但是,有一个警告:运算符的address可以重载以返回除address以外的其他值。 If you cannot guarantee that it won't be overloaded, use
std::addressof
instead. 如果您不能保证不会重载,请改用
std::addressof
。
Or simply use std::vector::data
as shown by Ivan. 或者直接使用
std::vector::data
,如Ivan所示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.