ArgMin for vector<double> in C++?

别来无恙 提交于 2020-08-24 05:57:28

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/10667867/argmin-for-vectordouble-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!