首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为具有多个数据成员的结构定义==和

为具有多个数据成员的结构定义==和
EN

Stack Overflow用户
提问于 2014-02-18 00:54:10
回答 2查看 180关注 0票数 4

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

代码语言:javascript
复制
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;
    }
};

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

EN

回答 2

Stack Overflow用户

发布于 2014-02-18 00:56:14

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

代码语言:javascript
复制
bool operator < (const nData& other) const {  // better make it const
    return std::tie(a,b,c) < std::tie(other.a, other.b, other.c);
}
票数 15
EN

Stack Overflow用户

发布于 2014-02-18 00:56:13

此结构易于扩展,并允许使用任意比较函数(例如strcmp)

代码语言:javascript
复制
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;
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21834854

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档