Operator< and strict weak ordering

前端 未结 6 1909
醉酒成梦
醉酒成梦 2020-11-22 03:51

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

6条回答
  •  隐瞒了意图╮
    2020-11-22 04:16

    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
    

    This orders the elements by a1 being most siginificant and a3 least significant.

    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

    Of course, if the comparison is expensive, you might want to cache the comparison result.


    [edit] removed wrong code


    [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;
    
    ...
    

提交回复
热议问题