为什么std :: max返回错误的值? [英] Why does std::max return the wrong value?

查看:174
本文介绍了为什么std :: max返回错误的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在CppCon 2014的 烧烤委员会会议中,委员会成员Walter Brown提到如果两个参数都具有相等的值,则std :: max返回错误的值。



这被接受而没有注释,因此不再赘述。他是什么意思?为什么要返回哪个值并不重要?

解决方案

如果 min max 仅用于有序集合,所有合理的定义都是等效的。



实际上, min max 用于预排序集合:在集合中,您可以具有两个元素,这些元素对相同的元素进行排序而不相同。例如,您可能正在操纵:

 结构学生{
char * name;
int等级;
};

并定义 s1< s2 strcmp(s1-> name,s2-> name)< 0 。然后,两个具有相同名称但不同年级的学生将进行相同的排序。对于(预)排序关系,这两个元素被称为等价



在一个预排序集合上,参数为<$ c两个等效元素的$ c> min 应该返回第一个参数,而 max 应该返回第二个参数。此定义保留了一些您期望的属性,最值得注意的是




  • 一对( min(x,y ) max(x,y))要么是( x y )或( y x ),






  • 如果 x y 是不同的,然后 min(x,y) max(x,y)是不同的,






  • 将( x y )映射到( min(x,y) max(x,y))是对两个元素集的稳定排序功能。



这不是一个新主意,在许多有关编程的标准文字中,您会找到比我更好的解释。 Mat和juanchopanza已经引用了 Stepanov论文的第7章,如果您喜欢C ++语法,则是很好的参考资料。 p>

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?

解决方案

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.

这篇关于为什么std :: max返回错误的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆