惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
T
Threatpost
Latest news
Latest news
N
News | PayPal Newsroom
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Help Net Security
Help Net Security
D
Darknet – Hacking Tools, Hacker News & Cyber Security
AI
AI
Simon Willison's Weblog
Simon Willison's Weblog
TaoSecurity Blog
TaoSecurity Blog
The Last Watchdog
The Last Watchdog
L
LINUX DO - 热门话题
Google DeepMind News
Google DeepMind News
T
Threat Research - Cisco Blogs
O
OpenAI News
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
The Exploit Database - CXSecurity.com
NISL@THU
NISL@THU
Application and Cybersecurity Blog
Application and Cybersecurity Blog
S
Securelist
小众软件
小众软件
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Martin Fowler
Martin Fowler
S
SegmentFault 最新的问题
Cisco Talos Blog
Cisco Talos Blog
云风的 BLOG
云风的 BLOG
AWS News Blog
AWS News Blog
GbyAI
GbyAI
N
News and Events Feed by Topic
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
美团技术团队
Engineering at Meta
Engineering at Meta
A
About on SuperTechFans
博客园 - 三生石上(FineUI控件)
S
Schneier on Security
博客园 - 聂微东
V2EX - 技术
V2EX - 技术
T
Troy Hunt's Blog
SecWiki News
SecWiki News
S
Secure Thoughts
B
Blog RSS Feed
Hugging Face - Blog
Hugging Face - Blog
WordPress大学
WordPress大学
腾讯CDC
H
Heimdal Security Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Apple Machine Learning Research
Apple Machine Learning Research
月光博客
月光博客
www.infosecurity-magazine.com
www.infosecurity-magazine.com
P
Privacy International News Feed

TinyEdi

Coroutine GDB with Python Bazel Notes Unix related things Shared Library I dreamt for so long The Building Blocks of Transformers A note for cmake A Strory of Mixin Tablegen Language Tutorial Lit and FileCheck IEEE 754 的 inf 比较问题 KD树与SKD树 汉诺塔问题-记录
比较运算符, Min, Max, Sort 和 Order
Edimetia3D · 2021-08-31 · via TinyEdi
未分类

惭愧,突然发现又是没有blog的一年。这一年不断在尝试搞大新闻,写点大东西,到现在也没憋出来。倒是又在学习新东西的过程中看到了一些零碎的小知识,很有意思.

很巧,这个也是和比较运算符相关的,和一年前的blog竟然有所重合。

还是先上结论: 当需要为类型T定义比较运算符时,所有运算符最好保证语义整体一致
* 一般来说,这很容易达到,我们只需要实现operator<(lhs,rhs),即可引申定义出其余几个比较运算符.
* 定义operator<=!(rhs < lhs)
* 定义operator>rhs < lhs
* 定义operator>=!(lhs < rhs)
* 定义operator=!(lhr < rhs) && !(rhs < 1hs)
* 定义operator!=lhs < rhs || rhs < lhs

问题背景: array={x,y}排序后, array[0]==Min(x,y) 一定成立吗

答案: 不一定. 当类型的比较运算符语义整体不一致时,就有可能触发这种问题.

例如 对于下面的代码

template <class T>
T* SortSwap(T* arr){
  if ( arr[1] < arr[0]) swap(arr[0],arr[1]);
  return arr;
}
T & Min(T&lhs,T&rhs){
    return (rhs < lhs)?rhs,lhs;
}

如果T 是一种 a<b, a>b, a==b 三者可同时为 False 的类型, 那么 SortSwap({x,y})[0] == Min(x,y) 将会是False

另外, 如果 Min的实现为return (lhs<rhs)?lhs:rhs , 那么上述的问题又解决了, 也就是说, 使用特殊的实现可以规避问题.

背后的原理可以参考
Notes on Programming