代码之家  ›  专栏  ›  技术社区  ›  jramm

更改不带大型条件块的比较运算符

  •  3
  • jramm  · 技术社区  · 10 年前

    我正在测试一个数字是否介于两个值之间。我让用户选择逻辑比较是否应该包括 equal to 无论是否有任何一个(或两个)限制。 他们通过定义 struct 其包含两个边缘值以及要使用的比较运算符:

    typedef struct {
        double low; 
        double high;
        bool low_equal; //false if a greater than operator (`>`) should be used, true if a greater-than-or-equal-to (`>=`) operator should be used
        bool high_equal; //Same as low_equal but for a less-than operator
    } Edges;
    

    一个数组 Edges 创建,(称为 bins 下面)和每个输入 value 我检查它是否位于垃圾箱边缘内。 然而,为了使用所需的一对比较运算符,我最终得到了这个可怕的条件块:

            if (bins[j].low_equal && bins[j].high_equal)
            {
                if (value >= bins[j].low && value <= bins[j].high)
                {
                    break;
                }
            }
            else if (bins[j].low_equal)
            {
                if (value >= bins[j].low && value < bins[j].high)
                {
                    data[i] = bins[j].value;
                    break;
                }
            }
            else if (bins[j].high_equal)
            {
                if (datum > bins[j].low && datum <= bins[j].high)
                {
                    break;
                }
            }
            else
            {
                if (value > bins[j].low && value < bins[j].high)
                {
                    break;
                }
            }
    

    有更好的方法吗?我可以通过某种方式设置操作员使用,然后直接呼叫他们吗?

    3 回复  |  直到 10 年前
        1
  •  4
  •   4386427    10 年前

    一种简单的方法可以是:

    bool higher = (value > bins[j].low) || (bins[j].low_equal && value == bins[j].low); 
    bool lower  = (value < bins[j].high) || (bins[j].high_equal && value == bins[j].high); 
    
    if (higher && lower)
    {
        // In range
    }
    
        2
  •  1
  •   Jarod42    10 年前

    可以在函数上使用指针

    bool less(double lhs, double rhs) { return lhs < rhs; }
    bool less_or_equal(double lhs, double rhs) { return lhs <= rhs; }
    using comp_double = bool(double, double);
    

    然后

    comp_double *low_comp = bins[j].low_equal ? less_or_equal : less;
    comp_double *high_comp = bins[j].high_equal ? less_or_equal : less;
    
    if (low_comp(bins[j].low, value) && high_comp(value, bins[j].high)) {
       // In range
    }
    
        3
  •  1
  •   6502    10 年前

    这将是IMO对三元运算符的一个很好的例子

    if ((bins[j].low_equal ? bins[j].low <= value : bins[j].low < value) &&
        (bins[j].high_equal ? value <= bins[j].high : value < bins[j].high)) {
       ...
    }
    
    推荐文章