Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementation of std::min [duplicate]

Tags:

c++

The implementation of std::min on cppreference and in the original stl looks like this:

return (b < a) ? b : a;

But I think this is slightly more readable:

return (a < b) ? a : b;

Which makes me wonder: are both implementations equivalent? Is there a particular reason why it is implemented like it is?

like image 273
StackedCrooked Avatar asked Jun 13 '13 13:06

StackedCrooked


2 Answers

The two different implementations would determine whether you choose the first or the second object as minimum if they are equal, which may make a difference for objects, if not for primitive types.

This, coupled with implementation of some other algorithms could have a larger impact. For example, if a sort algorithm uses min(a[i], a[j]) where i < j and a[i] and a[j] have the same value, the first implementation would result in no swap between the elements while the second does, making the sort unstable.


Note: As BoBTFish mentioned, the C++11 standard guarantees that both min and max return the left most minimum:

25.4.7:

3 Remarks: Returns the first argument when the arguments are equivalent

6 Remarks: Returns a copy of the leftmost argument when several arguments are equivalent to the smallest

like image 137
Shahbaz Avatar answered Nov 14 '22 10:11

Shahbaz


The implementations are not the same. What will happen in either implementation if a and b are equal? One will return a reference to a one will return a reference to b. The values of course are identical. But consider a struct in which the compare function only cared about one value, but some other values were different. This could have dramatic implications on sorting functions attempting to guarantee a stable sort.

Ultimately it's a style choice, in the event of equality should we return the first or second parameter? However, now that this style choice has been made, that it remains the same is very important, this is why things like standards definitions exist!

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf

Search for "25.4.7" regarding maximum and minimum.

like image 21
ChrisCM Avatar answered Nov 14 '22 09:11

ChrisCM