使用 STL 排序功能对列表进行排序

新手上路,请多包涵

我正在尝试按降序对包含 struct 项目的列表(类的一部分)进行排序,但它无法编译:

错误:’__last - __first’ 中的 ‘operator-’ 不匹配

sort(Result.poly.begin(), Result.poly.end(), SortDescending());

这是 SortDescending

 struct SortDescending
{
    bool operator()(const term& t1, const term& t2)
    {
        return t2.pow < t1.pow;
    }
};

谁能告诉我怎么了?

原文由 Vlad 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 545
2 个回答

标准算法 std::sort 需要随机访问迭代器,而 std::list<>::iterator 则不需要(列表迭代器是双向迭代器)。

您应该使用 std::list<>::sort 成员函数。

原文由 David Rodríguez - dribeas 发布,翻译遵循 CC BY-SA 2.5 许可协议

std::list has a built-in sort method that you need to use since std::sort only works with random access iterators, whereas std::list::iterator merely belongs到迭代器的双向迭代器类。

 Result.poly.sort(SortDescending());

此外,您的 operator () 应标记为 const

 struct SortDescending
{
    bool operator()(const term& t1, const term& t2) const
    {
        return t2.pow < t1.pow;
    }
};

最后,如果类型 term 重载了适当的 operator> 您可能不需要编写自己的比较器进行排序 - 只需使用 std::greater<T> (位于标准标题 <functional> ):

 Result.poly.sort(std::greater<term>());

原文由 Konrad Rudolph 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题