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

咨询:使用Lambda结合&&对结构体指针Vector排序是否可行

你的写法不可行,问题出在两个核心点:

1. Lambda参数类型不匹配

你的VectorA是std::vector<Test*>,容器里存储的是指针,因此std::sort传递给Lambda的元素是Test*类型,而非Test&。直接用Test&会触发编译错误,因为无法将指针隐式转换为引用。

2. 比较逻辑不符合排序规则

你写的(test.Current > test2.Current) && (test.Max > test2.Current)逻辑错误,且不满足std::sort要求的严格弱排序规则,会导致排序结果混乱甚至未定义行为:

  • 这不是常规的多字段排序逻辑(通常是先按第一个字段排序,字段相等时再按第二个字段排序)。
  • 举个反例:假设存在test1(Current=5, Max=3)和test2(Current=4, Max=6),此时test1和test2比较返回true&&false=false,test2和test1比较返回false&&false=false,违反了严格弱序的"不对称性"要求,std::sort无法正确处理这种情况。

修正后的代码

如果你的需求是先按Current降序排序,Current相等时再按Max降序排序,可以这样写:

struct Test
{
    int Current;
    int Max;
};

std::vector<Test*> VectorA;

std::sort(VectorA.begin(), VectorA.end(), [](const Test* t1, const Test* t2) {
    // 先比较Current,不等时直接返回结果
    if (t1->Current != t2->Current) {
        return t1->Current > t2->Current;
    }
    // Current相等时,比较Max
    return t1->Max > t2->Max;
});

也可以用更简洁的方式,利用std::make_pair的默认比较特性:

std::sort(VectorA.begin(), VectorA.end(), [](const Test* t1, const Test* t2) {
    return std::make_pair(t1->Current, t1->Max) > std::make_pair(t2->Current, t2->Max);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 16:21:50