Vla*_*lad 22 c++ sorting stl list
我正在尝试按降序排序列表(类的一部分)包含a的项目struct,但它不编译:
错误:'__last - __first'中'operator-'不匹配
sort(Result.poly.begin(), Result.poly.end(), SortDescending());
Run Code Online (Sandbox Code Playgroud)
这是SortDescending:
struct SortDescending
{
bool operator()(const term& t1, const term& t2)
{
return t2.pow < t1.pow;
}
};
Run Code Online (Sandbox Code Playgroud)
谁能告诉我什么是错的?
Dav*_*eas 37
标准算法std::sort需要随机访问迭代器,而std::list<>::iterator不是(列表迭代器是双向迭代器).
您应该使用std::list<>::sort成员函数.
Kon*_*lph 11
std::list有一个sort你需要使用的内置方法,因为std::sort它只适用于随机访问迭代器,而std::list::iterator只是属于迭代器的双向迭代器类.
Result.poly.sort(SortDescending());
Run Code Online (Sandbox Code Playgroud)
此外,你operator ()应该被标记const.
struct SortDescending
{
bool operator()(const term& t1, const term& t2) const
{
return t2.pow < t1.pow;
}
};
Run Code Online (Sandbox Code Playgroud)
最后,您不需要为此编写自己的比较器,只需使用std::greater<T>(位于标准头中<functional>):
Result.poly.sort(std::greater<term>());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16973 次 |
| 最近记录: |