为什么std :: max返回错误的值?

编程入门 行业动态 更新时间:2024-10-11 17:29:31
本文介绍了为什么std :: max返回错误的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

解决方案

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

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

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

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

在一个预排序集合上,参数为 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返回错误的值?

本文发布于:2023-11-22 01:15:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615402.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   std   max

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!