问题
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