给定一个 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/