使用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;
}
};
谁能告诉我出了什么问题吗?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
标准算法 std::sort 需要随机访问迭代器,而 std::list<>::iterator 则不需要(列表迭代器是双向迭代器)。
您应该使用
std::list<>::sort
成员函数。The standard algorithm
std::sort
requires random access iterators, whichstd::list<>::iterator
s are not (list iterators are bidirectional iterators).You should use the
std::list<>::sort
member function.std::list
有一个内置的sort
方法,您需要使用该方法,因为std::sort
仅适用于随机访问迭代器,而std::list::iterator
仅属于迭代器的双向迭代器类。另外,您的
operator ()
应标记为const
。最后,如果类型
term
重载了适当的operator>
,您可能不需要编写自己的比较器进行排序 - 只需使用std::greater< /code> (位于标准头
中):std::list
has a built-insort
method that you need to use sincestd::sort
only works with random access iterators, whereasstd::list::iterator
merely belongs to the bidirectional iterator class of iterators.Also, your
operator ()
should be markedconst
.Finally, if the type
term
overloads an appropriateoperator>
you might not need to write your own comparer for sorting — simply usestd::greater<T>
(located in the standard header<functional>
):似乎
Result.poly
的迭代器类型缺少operator -
。std::sort
不适用于std::list
更改为Result.poly.sort
It seems like the iterator types for
Result.poly
is missingoperator -
.std::sort
doesn't work withstd::list
change toResult.poly.sort