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

发布于 2024-08-25 15:19:46 字数 450 浏览 5 评论 0原文

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

谁能告诉我出了什么问题吗?

I'm trying to sort a list (part of a class) in descending order containing items of a struct, but it doesn't compile:

error: no match for 'operator-' in '__last - __first'

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

And here's SortDescending:

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

Can anyone tell me what's wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

长亭外,古道边 2024-09-01 15:19:46

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

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

The standard algorithm std::sort requires random access iterators, which std::list<>::iterators are not (list iterators are bidirectional iterators).

You should use the std::list<>::sort member function.

时常饿 2024-09-01 15:19:46

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; 
    }
};

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

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

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 to the bidirectional iterator class of iterators.

Result.poly.sort(SortDescending());

Also, your operator () should be marked const.

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

Finally, if the type term overloads an appropriate operator> you might not need to write your own comparer for sorting — simply use std::greater<T> (located in the standard header <functional>):

Result.poly.sort(std::greater<term>());
許願樹丅啲祈禱 2024-09-01 15:19:46

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

It seems like the iterator types for Result.poly is missing operator -. std::sort doesn't work with std::list change to Result.poly.sort

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文