简体   繁体   English

获取给定地址的 std::vector 元素的索引

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

Let's say I have a std::vector and I get by some means the address of the n-th element.假设我有一个 std::vector 并且我通过某种方式获得了第 n 个元素的地址。 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?给定我的 std::vector 的基地址,是否有一种简单的方法(比遍历向量更快)来获取元素出现的索引? Let's assume I'm sure the element is in the vector.让我们假设我确定元素在向量中。

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. 请注意,从技术上讲,连续保证是在C ++ 03中引入的,但我还没有听说过C ++ 98实现不会发生这种情况。

distance( xxx.begin(), theIterator); 距离(xxx.begin(),theIterator);

The above will only work for a vector::iterator. 以上内容仅适用于vector :: iterator。 If you only have a raw pointer to an element, you must use it this way: 如果您只有一个指向元素的原始指针,则必须以这种方式使用它:

distance(&v[0], theElementPtr); 距离(&v [0],theElementPtr);

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;
}

On the way of learning, I have taken the following notes:在学习的路上,我做了以下笔记:

#include <iostream>
#include <vector>

int main() {
    std::vector<std::string> words={"This","is","just","a","trial!"};
    size_t i; //using the contiguous property of a vector:
    for (auto const& elem : words) {
        i = &elem - &*words.begin();// or
        i = &elem - &words.front();// or 
        i = &elem - words.data();// or
        i = std::addressof(elem) - std::addressof(words[0]); 
        if(std::addressof(elem) == &words.front())
          std::cout << elem <<" (at"<<&elem<<") relative to ("<< &words[0] << ") takes position @#"<<i<< std::endl;
        else std::cout << elem <<" (at"<<&elem<< ") takes position @#"<<i<< std::endl;
    }
    return 0;
}

Test run here .试运行在这里 It is open to further study (or learn from masters) which one is the most secured/safe and/or most efficient approach.可以进一步研究(或向大师学习)哪一种是最安全/最安全和/或最有效的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM