我有一个用这个结构填充的列表:
struct singlePaymentStruct
{
std::string payer;
int payment;
double amount;
std::time_t timeRec;
singlePaymentStruct() {
payer="Empty";
payment=0;
amount=0;
timeRec = time(0);
}
};
我希望能够按任何字段对列表进行排序。我该怎么做? 我不太明白 sort 方法如何处理比记录列表更复杂的东西......
找到的解决方案:
singlePaymentList.sort( []( const singlePaymentStruct &a, const singlePaymentStruct &b)
{return a.payer > b.payer;}
);
最佳答案
1.重载运算符<
你可以通过重载<运算符来做到这一点
struct Foo{
int bar;
bool operator<(Foo &x){
return bar < x.bar;
}
};
2.使用lambda表达式 (what is lambda expression?)
Foo array[10];
std::sort(array,array + 10,[](Foo const &l, Foo const &r) {
return l.bar < r.bar; });
3.使用自定义比较函数
如果事先知道可能用于排序的字段,则可能更容易阅读以实现专门用于排序的自定义比较函数。
struct Foo {
int bar;
SpecialType daa; // Assume daa.IsLessThan() available.
static bool lessBar(const Foo& l, const Foo& r) {
return l.bar < r.bar;
}
static bool lessDaa(const Foo& l, const Foo& r) {
return l.daa.IsLessThan(r.daa);
}
};
Foo array1[10]; // To be sorted by Foo::bar
Foo array2[10]; // To be sorted by Foo::daa
std::sort(array1, array1+10, Foo::lessBar);
std::sort(array2, array2+10, Foo::lessDaa);
关于c++ - 在 C++ 中按结构成员对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41409390/