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?
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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With