c++ - 如何返回 vector 中元素的索引

标签 c++ pointers vector indexing

给定一个 vector

vector<classX *> myVec;

如何返回其元素之一的索引 i,如下面的函数;

size_t nearestElement(classY const& p){
     size_t i(0);
     double d = distance(myVec[i]->position(), p);
     for (auto const& element : myVec){
         if(distance(element->position(), p) < d){
            i = ???; // the index of the current element
         }
     return i;
     }
}

其中 position() 是在 classX 中定义的函数,而 distance 不是 std::distance函数,但是我自己定义的函数。

最佳答案

将基于 for 的范围更改为常规 for,或将索引变量添加到您当前的 for:

int index = 0;
for (auto const& element : myVec){          
     if(distance(element->position(), p) < d){
        i = index; // the index of the current element
     }
     index++
...

关于c++ - 如何返回 vector 中元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23222464/

相关文章:

c++ - 尝试使用 Boost 序列化库时出错

c++ - 处理未将任何函数标记为 const 的库的最佳方法是什么?

C编程: Linked Lists

java - 指向 Java LinkedList 节点的指针

c++ - 用户定义的不同大小 vector 的减少

c++ - 来自一维 vector 转置的平均 vector

c++ - 了解 C++ 中的 vector 初始化

c++ - boost::asio::io_service 事件循环中的事件数

c++ - 从 MPI_Scatter 到 MPI_Scatterv

c++ - 是否可以覆盖指向 C++ 中对象的指针的数组访问运算符?