操作员和严格的弱排序 [英] Operator< and strict weak ordering

查看:131
本文介绍了操作员和严格的弱排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在n元组(例如3元组)上定义运算符< ,以便满足严格弱排序概念?我知道boost库有正确定义运算符< 的tuple类,但由于某些原因,我不能使用它。

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] a [i]。算法的替代表达式将是skip while equal,then compare:

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.

代码

这篇关于操作员和严格的弱排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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