In the "Grill the Committee" session from CppCon 2014, Committee member Walter Brown mentioned that std::max returns the wrong value in the case that both arguments have an equal value.
This was accepted without comment, and not elaborated upon. What did he mean by this? Why should it matter which value is returned?
std::max is defined in the header file <algorithm> and is used to find out the largest of the number passed to it. It returns the first of them, if there are more than one.
If min
and max
are only used on ordered sets, all reasonable definitions are equivalent.
In practice, however, min
and max
are used on preordered sets: sets in which you can have two elements that sort the same without being identical. For example, you could be manipulating:
struct student { char *name; int grade; };
and define s1 < s2
when strcmp(s1->name, s2->name) < 0
. Then two students with the same name but different grades will sort the same. Such two elements are said to be equivalent for the (pre)ordering relation.
On a preordered set, the argument goes, min
of two equivalent elements should return the first parameter, and max
should return the second. This definition preserves a few properties that you'd expect, most notably
min(x,y)
, max(x,y)
) is either (x
,y
) or (y
,x
),and
x
and y
are distinct, then min(x,y)
and max(x,y)
are distinct,and
x
,y
) to (min(x,y)
, max(x,y)
) is a stable sorting function for sets of two elements.This is not a new idea, and you'll find way better explanations than mine in a number of standard texts on programming. Chapter 7 of the Stepanov Papers, already cited by Mat and juanchopanza, is a good source if you like C++ syntax.
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