You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++对类对象vector排序时如何减少自定义排序函数的数量?

解决方案

方案1:直接使用Lambda表达式(简单快捷,适合单次排序场景)

C++11及以上版本支持在sort函数的第三个参数位置直接写匿名lambda函数,不需要提前单独定义全局比较函数:

// 按 firstName 排序
sort(records.begin(), records.end(), [](studentrecord* a, studentrecord* b) {
    return a->getfirstname() < b->getfirstname();
});
// 按 lastName 排序
sort(records.begin(), records.end(), [](studentrecord* a, studentrecord* b) {
    return a->getlastname() < b->getlastname();
});
// 按 grade 排序
sort(records.begin(), records.end(), [](studentrecord* a, studentrecord* b) {
    return a->getgrade() < b->getgrade();
});

后续新增排序字段时,只需要修改lambda里调用的getter方法即可,不需要新增全局函数。

方案2:封装通用比较模板(适合多场景复用排序规则)

可以封装一个通用的模板函数,接收类的成员getter函数作为参数,自动生成对应的比较器,新增排序字段时无需新增任何比较代码:

第一步:先修改原有类的getter方法,加上const修饰(符合const正确性规范,避免编译错误)

// 修改三个get方法的签名,末尾加const
string getfirstname() const {
    return firstname;
}
string getlastname() const {
    return lastname;
}
string getgrade() const {
    return grade;
}

第二步:定义通用比较模板

template<typename T>
auto compareBy(string (T::*getter)() const) {
    return [getter](const T* a, const T* b) {
        return (a->*getter)() < (b->*getter)();
    };
}

第三步:使用模板生成比较器

后续不管新增多少个排序字段,只要类里有对应的const getter方法,直接传入getter的地址即可使用:

displayRecords(records);
// 按 firstName 排序
sort(records.begin(), records.end(), compareBy(&studentrecord::getfirstname));
displayRecords(records);
// 按 lastName 排序
sort(records.begin(), records.end(), compareBy(&studentrecord::getlastname));
displayRecords(records);
// 按 grade 排序
sort(records.begin(), records.end(), compareBy(&studentrecord::getgrade));
displayRecords(records);
// 后续新增比如按学号排序,只需要一行:
// sort(records.begin(), records.end(), compareBy(&studentrecord::getid));

内容的提问来源于stack exchange,提问作者Ross Aylen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 00:18:03