gpt4 book ai didi

c++ - 为具有许多数据成员的结构定义 == 和 <

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:57:18 25 4
gpt4 key购买 nike

如果结构具有任意多个数据成员,如何概括 < 的定义(< 将使用列出数据成员的顺序来定义)?一个包含 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;
}
};

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

最佳答案

您可以使用 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);
}

关于c++ - 为具有许多数据成员的结构定义 == 和 <,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21834854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com