C++ Primer:可以将严格弱序看作“小于等于”?


1. 背景

  在阅读到C++Primer中文版(第5版)的有序容器的关键字类型(P378)时, 发现书中是将严格弱序看作“小于等于”,而且在其列出的基本性质中还写道:两个关键字不能同时“小于等于”对方
  虽然已经对小于等于加引号表示不是真的,但个人觉得非常别扭,其说法也是矛盾的,例如k1<=k2,那k2<=k1应该是可行的。

原文:

有序容器的关键字类型
  可以向一个算法提供我们自己定义的比较操作(参见10.3节,第344页),与之类似,也可以提供自己定义的操作来替代关键字上的<运算符。所提供的操作必须在关键字类型上定义一个严格弱序(strict weak ordering)。可以将严格弱序看作“小于等于”,虽然实际定义的操作可能是一个复杂的函数。无论我们怎么定义比较函数,它必须具备如下基本性质:

  • 两个关键字不能同时“小于等于”对方:如果k1“小于等于”k2,那么k2绝不能“小于等于”k1。
  • 如果k1“小于等于”k2,且k2“小于等于”k3,那么k1必须“小于等于”k3。
  • 如果存在两个关键字,任何一个都不“小于等于”另一个,那么我们称这两个关键字是“等价”的。如果k1“等价于”k2,且k2“等价于”k3,那么k1必须“等价于”k3。

如果两个关键字是等价的(即,任何一个都不“小于等于”另一个),那么容器将它们视作相等来处理。当用作map的关键字时,只能有一个元素与这两个关键字关联,我们可以用两者中任一个来访问对应的值。

2. 分析理解

  当前所看的C++Primer是中文版,遇到不易理解或感觉有错地方,首先应找英文原版对应的段落来比较。从如下英文段落中可明显看出,书中是将“less than”翻译成“小于等于”,但无论在百度翻译和有道翻译中,“less than”都被翻译成“小于”。

英文:

Just as we can provide our own comparison operation to an algorithm (§ 10.3, p.385), we can also supply our own operation to use in place of the < operator on keys. The specified operation must define a strict weak ordering over the key type. We can think of a strict weak ordering as “less than”, although our function might use a more complicated procedure. However we define it, the comparison function must have the following properties:

  • Two keys cannot both be “less than” each other; if k1 is “less than” k2, then
    k2 must never be “less than” k1.
  • If k1 is “less than” k2 and k2 is “less than” k3, then k1 must be “less than”
    k3.
  • If there are two keys, and neither key is “less than” the other, then we’ll say
    that those keys are “equivalent.” If k1 is “equivalent” to k2 and k2 is “equivalent” to k3, then k1 must be “equivalent” to k3.

If two keys are equivalent (i.e., if neither is “less than” the other), the container treats them as equal. When used as a key to a map, there will be only one element associated with those keys, and either key can be used to access the corresponding value.

  同时,从网上搜索相关资料(C++ 严格弱序)等)可知:“<”是严格弱序,而“<=”不是严格弱序
  故个人总结,“小于等于”应该是翻译错误,使用“小于”更合适

  • 12
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值