向量的ArgMin在C ++中? [英] ArgMin for vector<double> in C++?
问题描述
我想在C ++ std :: vector< double>
中找到最小值的索引。这是一个较为冗长的实现:
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.)
我认为上述实现可能是对车轮的彻底改造;如果可能的话,我想使用内置代码。为此,是否有对STL函数的单行调用?或者,有人可以建议更简洁的实现吗?
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?
推荐答案
您可以使用标准的 min_element
函数:
You could use the standard min_element
function:
std::min_element( vec.begin(), vec.end() );
它将迭代器返回迭代器范围内的最小元素。由于您需要索引并且正在使用 vector
s,因此可以从 vec.begin()$ c $中减去所得的迭代器。 c>获取此类索引。
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.
如果需要自定义比较,则函数或函数对象还有一个额外的重载。
There is an additional overload for a function or function-object if you need a custom comparison.
这篇关于向量的ArgMin在C ++中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!