【发布时间】:2012-05-19 18:32:49
【问题描述】:
我想找到 C++ std::vector<double> 中最小值的索引。这是一个有点冗长的实现:
//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;
}
(如果您发现上述实现中有任何错误,请告诉我。我测试了它,但我的测试并不详尽。)
我认为上面的实现可能是一个轮子改造;如果可能的话,我想使用内置代码。为此,是否有对 STL 函数的单行调用?或者,有人可以建议更简洁的实现吗?
【问题讨论】:
-
std::min_element不会“返回所有分钟”。它返回一个迭代器,指向范围内的最小元素。如果最小值出现多次,则迭代器指向第一个。你的mins[0]应该是*mins,因为它是一个迭代器,而不是一个结果数组。
标签: c++ collections stl vector