I don't think there is anything wrong with your solution for an array of floating-point elements (I assume that there are no NaNs). std::min
returns a reference to its argument with a lower value (which is defined for non-nan FP numbers). Thus std::min(arr[i], arr[min_index])
:
- either returns a reference to
arr[i]
if it is less or equal to arr[min_index]
,
- or, returns a reference to
arr[min_index]
, if this is greater than arr[i]
.
In 1., when you compare the result of std::min
with arr[i]
, you are comparing two very same FP objects, which is guaranteed to be evaluated ot true
.
In 2., you are comparing two FP objects with different values, which is guaranteed to be evaluated to false
.
Therefore, I think your solution works well.
Just be aware that rounding errors outside of your this solution can seemingly break it. Consider the following example:
float arr[3] = { 1.0f / 3.0f, 0.33333334, 2.0f };
size_t min_index = 0;
for (size_t i = 1; i < 3; i++)
min_index = std::min(arr[i], arr[min_index]) == arr[i] ? i : min_index;
std::cout << min_index;
1/3 is the smallest number, but this printed out 1 in my experiment, since what your code is comparing is a computer representation of 1.0f/3.0f
with a computer representation of 0.33333334
, which both are subjects of rounding. Consequently, the numbers actually stored in arr
, are different.