Operatorlt; and strict weak ordering(操作员和严格的弱排序)
问题描述
如何在 n 元组(例如在 3 元组上)定义 operator<
使其满足 严格弱排序 概念?我知道 boost 库具有正确定义的 operator<
元组类,但由于某些原因我不能使用它.
How to define operator<
on n-tuple (for example on 3-tuple) so that it satisfy strict weak ordering concept ? I know that boost library has tuple class with correctly defined operator<
but for some reasons I can't use it.
推荐答案
if (a1 < b1)
return true;
if (b1 < a1)
return false;
// a1==b1: continue with element 2
if (a2 < b2)
return true;
if (b2 < a2)
return false;
// a2 == b2: continue with element 3
if (a3 < b3)
return true;
return false; // early out
这按照 a1 最重要和 a3 最不重要对元素进行排序.
This orders the elements by a1 being most siginificant and a3 least significant.
这可以无限期地继续,您也可以例如将其应用于 T 的向量,迭代 a[i] < 的比较.a[i+1]/a[i+1] <[i].该算法的另一种表达是在相等时跳过,然后比较":
This can be continued ad infinitum, you could also e.g. apply it to a vector of T, iterating over comparisons of a[i] < a[i+1] / a[i+1] < a[i]. An alternate expression of the algorithm would be "skip while equal, then compare":
while (i<count-1 && !(a[i] < a[i+1]) && !(a[i+1] < a[i])
++i;
return i < count-1 && a[i] < a[i+1];
当然,如果比较的开销很大,您可能需要缓存比较结果.
Of course, if the comparison is expensive, you might want to cache the comparison result.
[edit] 删除了错误的代码
[edit] removed wrong code
[edit] 如果不仅仅是 operator<
可用,我倾向于使用模式
[edit] if more than just operator<
is available, I tend to use the pattern
if (a1 != b1)
return a1 < b1;
if (a2 != b2)
return a2 < b2;
...
这篇关于操作员<和严格的弱排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:操作员<和严格的弱排序
- 将 hdc 内容复制到位图 2022-09-04
- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
- OpenGL 对象的 RAII 包装器 2021-01-01
- DoEvents 等效于 C++? 2021-01-01
- 将函数的返回值分配给引用 C++? 2022-01-01
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
- 如何提取 __VA_ARGS__? 2022-01-01
- XML Schema 到 C++ 类 2022-01-01
- 哪个更快:if (bool) 或 if(int)? 2022-01-01
- GDB 不显示函数名 2022-01-01