Gamba Osaca
Gamba Osaca

Reputation: 307

how to return index of element in vector

Given a vector

vector<classX *> myVec;

how to return the index i of one of its elements as in the following function;

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

where position() is a function defined in classX and distance is not the std::distance function, but a function I defined my self.

Upvotes: 0

Views: 3970

Answers (2)

Jarod42
Jarod42

Reputation: 218238

&element - &myVec[0] should do the trick for container with continuous data (as std::vector).

if your distance function is cheap, you may rewrite your function like this:

size_t nearestElement(classY const& p)
{
    auto it = std::min_element(myVec.begin(), myVec.end(),
        [&p](const classX* lhs, const classX* rhs) {
            return distance(lhs->position(), p) < distance(rhs->position(), p);
        });
    return it - myVec.begin(); // Will return 0 if myVec is empty.
}

Upvotes: 1

marcinj
marcinj

Reputation: 50036

Change range based for to regular for, or add indexing variable to your current for:

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

Upvotes: 2

Related Questions