【问题标题】:Sort a list of pointers to objects using lambda expression使用 lambda 表达式对指向对象的指针列表进行排序
【发布时间】:2026-02-03 02:40:01
【问题描述】:

我正在尝试按照 Pilot 对象在比赛中所用的时间对指向 Pilot 对象的指针列表进行排序。时间是通过 Pilot 类中的 compet 方法计算的。所以我将通过方法而不是类属性对它们进行排序。 涉及问题的类:

class Pilot
{
    double compete(Race *race); // Computes the time the pilot takes to finish the race
}
class Race
{
    list<Pilot*> pilots; // Pilots competing

    void sortByTime();
}

我想使用 lambda 表达式对列表进行排序。这是我的尝试:

void Race::sortByTimes()
{ 
    sort(pilots.begin(), pilots.end(), [this](Pilot *p1, Pilot *p2) -> bool
    {
        return p1->compete(this) < p2->compete(this);
    });
}

算法库中有 5 个编译错误:

Error C2784 'unknown.type std::operator - (std::move_iterator<_RanIt> &, const std::move_iterator<_RanIt2> &)' : could not deduce template argument for 'std::move_iterator<_RantIt> &' from 'std::_List_iterator<std::_List_val<std::_List_simple_types<PilotoOficial*>>>'

std::reverse_iterator 和 std::_Revranit 中还有两个 C2784 错误

Error C2676 binary : 'std::_List_iterator<std::_List_val<std::_List_simple_types<Pilot*>>>' : does not define this operator or a conversion to a type acceptable to the predefined operator

Error C2780 'void std::_Sort(_RanIt,_RanIt,_Diff,_Pr' : expects 4 arguments; 3 provided

【问题讨论】:

  • 您的 lambda 参数后不需要 -&gt; bool

标签: c++ list sorting lambda


【解决方案1】:

使用std::list::sortstd::sort 需要随机访问迭代器,而您已经给了它双向迭代器。另一种选择是使用像 std::vector 这样具有随机访问迭代器的容器。

【讨论】: