简体   繁体   English

ArgMin for C ++中的vector <double>?

[英]ArgMin for vector<double> in C++?

I'd like to find the index of the minimum value in a C++ std::vector<double> . 我想在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? 是否对STL函数进行单行调用? Or, can someone suggest a more concise implementation? 或者,有人可以建议更简洁的实施吗?

You could use the standard min_element function: 您可以使用标准的min_element函数:

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 vector s, you can then substract the resulting iterator from vec.begin() to get such index. 由于您需要索引并且正在使用vector s,因此可以从vec.begin()减去生成的迭代器以获取此类索引。

There is an additional overload for a function or function-object if you need a custom comparison. 如果需要自定义比较,则函数或函数对象会有额外的重载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM