Why does std::max return the wrong value? [duplicate]

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

  • the pair (min(x,y), max(x,y)) is either (x,y) or (y,x),

and

  • if x and y are distinct, then min(x,y) and max(x,y) are distinct,

and

  • the function that maps (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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)