Std :: min implementation

The implementation of std::min on cppreference and in the original stl is as follows:

 return (b < a) ? b : a; 

But I think this is a little readable:

 return (a < b) ? a : b; 

Which makes me wonder: are both implementations equivalent? Is there a special reason why it is implemented as if it is?

+4
source share
3 answers

Two different implementations determine whether you will choose the first or second object as minimal, if they are equal, which may matter for objects, if not for primitive types.

This, combined with the implementation of some other algorithms, may have a greater impact. For example, if the sorting algorithm uses min(a[i], a[j]) , where i < j and a[i] and a[j] have the same value, the first implementation will not lead to an exchange between the elements until the second does, making sorting unstable.


Note. As BoBTFish mentioned, the C ++ 11 standard ensures that both min and max return a minimum on the left:

25.4.7:

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

6 Notes: Returns a copy of the leftmost argument when multiple arguments are equivalent to the smallest

+6
source

The implementations do not match. What happens in any implementation if a and b are equal? One will return a link to one, will return a link to b. The course values โ€‹โ€‹are identical. But consider a structure in which the comparison function only took care of one value, but some other values โ€‹โ€‹were different. This can have serious implications for sorting functions trying to guarantee a consistent look.

Ultimately, this is the choice of style, in case of equality, should we return the first or second parameter? However, now that this choice of style is made, that it remains the same, it is very important, so there are things like definitions of standards!

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

Find "25.4.7" relative to the high and low.

+4
source

- INCORRECT RESPONSE - SEE COMMENTS - bb

FWIW, it was not my observation that the STL was written to be especially easy to read, necessarily, but it is beautifully simple; in this case, the only possible way to get the same result would be

 return (a <= b) ? a : b; 

which would be another character, and, IMHO, actually not so easy to read. Also, see @Shahbaz's comment above on sorting stability. Operations such as min have clear behaviors for inclusiveness and exclusivity.

TL DR, because Less is not the same as Less or Equal

See comments below - this answer will be correct, like a macro in C, but actually incorrect in C ++ for the reasons described in the comments below. I mark this as incorrect, but leave it because the comments are useful and important for understanding. I apologize if I confuse the problem for everyone.

-1
source

Source: https://habr.com/ru/post/1486029/


All Articles