sol*_*les 10 c++ collections stl vector
我想在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;
}
Run Code Online (Sandbox Code Playgroud)
(如果你发现上述实现中有任何错误,请告诉我.我测试了它,但我的测试并不详尽.)
我认为上述实施可能是一个轮子改造; 如果可能的话,我想使用内置代码.是否有对STL功能的单行调用?或者,有人可以建议更简洁的实施吗?
K-b*_*llo 18
您可以使用标准min_element功能:
std::min_element( vec.begin(), vec.end() );
Run Code Online (Sandbox Code Playgroud)
它将迭代器返回到迭代器范围中的最小元素.既然你想要一个索引并且你正在使用vectors,那么你可以从中vec.begin()得到这个索引来减去生成的迭代器.
如果需要自定义比较,则函数或函数对象会有额外的重载.