假设我有一个普通的旧数据(POD)
struct
包含多个数字字段。
我想重载比较运算符,以便比较POD的两个实例。
问题是,我需要为那些操作员(比如操作员)设置过载
less()
-对于POD中的每个数字字段。
显然,以下方法不起作用,因为编译器无法区分这两个版本:
struct my_struct{
int a;
int b;
int c;
};
bool operator<(const my_struct& one, const my_struct& two) {
return one.a < two.a;
}
bool operator<(const my_struct& one, const my_struct& two) {
return one.b < two.b;
}
所以我编写了自己的自定义函数
lessThan()
,它接受一个标志并完成这项工作,但我并不特别喜欢这个解决方案(in
MWE
下面)因为我不能使用
<
就像我很容易用比较运算符一样。
#include <iostream>
#include <iomanip>
struct my_struct{
int a;
int b;
int c;
};
bool lessThan(const my_struct& one, const my_struct& two, const char flag) {
switch (flag) {
case 'a':
return one.a < two.a;
break;
case 'b':
return one.b < two.b;
break;
case 'c':
return one.c < two.c;
break;
default:
throw("Either case a, b, or c\n");
break;
}
}
int main()
{
my_struct one{1, 3, 4};
my_struct two{2, 2, 4};
std::cout << "one < two: " << std::boolalpha
<< lessThan(one, two, 'a') << std::endl;
return 0;
}
是否有方法为自定义POD创建多个比较运算符重载
结构
s有许多数字字段,每个重载都比较其中一个字段?
(为了给你更多的上下文,我需要这些重载来根据文件的任何特征对文件数组进行排序:例如按维度、按上次修改日期、按包含的文件或子目录的数量等。
在上述简化示例中,每个POD实例都抽象出一个文件。)
编辑:
预期用途示意图:
sortAccordingToFieldA(std::vector<my_struct>& my_vec, int a){
for (auto i : my_vec) {
for (auto j : [std::find(my_vec.begin(), my_vec.end(), i)+1, my_vec.end()] ) {
if (i < j)
}
}
}