Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArgMin for vector<double> in C++?

I'd like to find the index of the minimum value in a C++ std::vector<double>. Here's a somewhat verbose implementation of this:

//find index of smallest value in the vector
int argMin(std::vector<double> vec)
{
    std::vector<double>::iterator mins = std::min_element(vec.begin(), vec.end()); //returns all mins
    double min = mins[0]; //select the zeroth min if multiple mins exist
    for(int i=0; i < vec.size(); i++)
    {
        //Note: could use fabs( (min - vec[i]) < 0.01) if worried about floating-point precision
        if(vec[i] == min)    
            return i;
    }
    return -1;
}

(Let me know if you notice any mistakes in the above implementation. I tested it, but my testing is not at all exhaustive.)

I think the above implementation is probably a wheel-reinvention; I'd like to use built-in code if possible. Is there a one-line call to an STL function for this? Or, can someone suggest a more concise implementation?

like image 709
solvingPuzzles Avatar asked May 19 '12 18:05

solvingPuzzles


1 Answers

You could use the standard min_element function:

std::min_element( vec.begin(), vec.end() );

It returns an iterator to the minimum element in the iterator range. Since you want an index and you are working with vectors, you can then substract the resulting iterator from vec.begin() to get such index.

There is an additional overload for a function or function-object if you need a custom comparison.

like image 139
K-ballo Avatar answered Oct 21 '22 08:10

K-ballo