如果结构有任意多个数据成员,如何推广<的定义(使用数据成员的列出顺序定义<)?一个包含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;
}
};以某种方式使用可变模板和递归?
发布于 2014-02-18 00:56:14
您可以使用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);
}发布于 2014-02-18 00:56:13
此结构易于扩展,并允许使用任意比较函数(例如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;https://stackoverflow.com/questions/21834854
复制相似问题