Get the index of a std::vector element given its address

别来无恙 提交于 2019-12-12 08:27:42

问题


Let's say I have a std::vector and I get by some means the address of the n-th element. Is there a simple way (faster than iterating through the vector) to get the index at which the element appears, given the base address of my std::vector? Let's assume I'm sure the element is in the vector.


回答1:


Since you know the element is within the vector, and vector guarantees that its storage is contiguous, you could do:

index = element_pointer - vector.data();

or

index = element_pointer - &vector[0];

Note that technically the contiguous guarantee was introduced in C++03, but I haven't heard of a C++98 implementation that doesn't happen to follow it.




回答2:


distance( xxx.begin(), theIterator);

The above will only work for a vector::iterator. If you only have a raw pointer to an element, you must use it this way:

distance(&v[0], theElementPtr);




回答3:


Yes - because a vector guarantees all elements are in a contiguous block of memory you can use pointer arithmetic to find it like so

#include <iostream>
#include <vector>

int main(int argc, char *argv[])
{
   std::vector<int> vec;

   for(int i=0; i<10; ++i)
   {
      vec.push_back(i);
   }

   int *ptr=&vec[5];
   int *front=&vec[0];

   std::cout << "Your index=" << ptr-front << std::endl;
   return 0;
}


来源:https://stackoverflow.com/questions/8159082/get-the-index-of-a-stdvector-element-given-its-address

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!