samedi 31 octobre 2015

Seek item within vector

I have a vector of real values, sorted by increasing order.

These values can be within the range [0, 1]. Then I pick a value x within this range and I need to find which is the index of the smaller value greater or equal to x.

I can solve this problem by iterating over the whole array:

vector<double> values;
double x;

for (auto val : values)
{
    if (x <= values)
    {
        // found
        break;
    }
}

Is there a faster way to get the same result? I was thinking about a binary search, but how to implement it?

Aucun commentaire:

Enregistrer un commentaire