定义==和<对于具有许多数据成员的结构

时间:2014-02-17 16:54:10

标签: c++ struct inequality

如何概括<的定义如果结构有任意多个数据成员(<将使用列出数据成员的顺序定义)?一个包含3个数据成员的简单示例:

struct nData {
    int a;
    double b;
    CustomClass c;   // with == and < defined for CustomClass
    bool operator == (const nData& other) {return (a == other.a) && (b == other.b) && (c == other.c);}
    bool operator < (const nData& other) {
        if (  (a < other.a)  ||  ((a == other.a) && (b < other.b))  ||
                ((a == other.a) && (b == other.b) && (c < other.c))  )
            return true;
        return false;
    }
};

以某种方式使用可变参数模板和递归?

2 个答案:

答案 0 :(得分:15)

您可以使用std::tie创建对类成员的引用元组,并使用为元组定义的词典编码比较运算符:

bool operator < (const nData& other) const {  // better make it const
    return std::tie(a,b,c) < std::tie(other.a, other.b, other.c);
}

答案 1 :(得分:3)

此结构可轻松扩展,并允许使用任意比较函数(例如strcmp

if (a != other.a) return a < other.a;
if (b != other.b) return b < other.b;
if (c != other.c) return c < other.c;
return false;