【问题标题】:Sort list using STL sort function使用 STL 排序功能对列表进行排序
【发布时间】:2011-01-26 19:59:39
【问题描述】:

我正在尝试按降序对包含 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; 
    }
};

谁能告诉我怎么了?

【问题讨论】:

标签: c++ list stl sorting


【解决方案1】:

std::list 有一个内置的sort 方法,您需要使用它,因为std::sort 仅适用于随机访问迭代器,而std::list::iterator 仅属于迭代器的双向迭代器类。

Result.poly.sort(SortDescending());

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

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

最后,您不需要为此编写自己的比较器,只需使用std::greater&lt;T&gt;(位于标准标头&lt;functional&gt;):

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

【讨论】:

  • 不,这不是t it, there's nothing in the standard that says that this needs to be const. If you look at the error message it seems like operator - 输入迭代器缺少`。
  • 如果重新排序会得到更好的答案(这里的常量是一个附带问题)。
  • 仍然无法使用我自己的比较器或使用更大的()它仍然会给出一堆错误
  • @Andreas:我担心一个临时对象被传递到sort 函数中。我忘记了比较器是按值传递的,并且由于临时对象不能绑定到非const 引用,这需要函数为const
  • @Vlad:什么错误?这段代码应该可以工作。您是否包含 std::greater 的标题 &lt;functional&gt;
【解决方案2】:

标准算法std::sort 需要随机访问迭代器,std::list&lt;&gt;::iterators 不需要(列表迭代器是双向迭代器)。

您应该使用std::list&lt;&gt;::sort 成员函数。

【讨论】:

  • 但我不知道如何正确地为我的班级重载 less 运算符
  • @Vlad,你不需要超载任何东西。 Result.poly.sort(SortDescending()); 应该可以正常工作。
  • 比较器中的operator ()应该仍然标记为const,因为它不会修改任何成员。
【解决方案3】:

Result.poly 的迭代器类型似乎缺少 operator -std::sort 不适用于 std::list 更改为 Result.poly.sort

【讨论】:

  • 但我不知道如何正确地为我的班级重载 less 运算符
  • @Vlad 你可以用Result.poly.sort(SortDescending()) 打电话,不需要operator &lt;
  • @Konrad 我想他说的是operator &lt;,但忽略了std::ist::sort 有一个带有谓词的版本。
猜你喜欢
  • 2014-05-30
  • 1970-01-01
  • 2014-06-29
  • 2018-08-26
  • 1970-01-01
  • 2021-07-25
  • 1970-01-01
  • 1970-01-01
  • 2015-11-01
相关资源
最近更新 更多