Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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?

like image 644
Kaz Dragon Avatar asked Oct 27 '14 09:10

Kaz Dragon


People also ask

What does STD Max return?

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.


1 Answers

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.

like image 197
jch Avatar answered Oct 08 '22 22:10

jch