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?
The C++ function std::list::sort() sorts the elements of the list in ascending order. The order of equal elements is preserved. It uses operator< for comparison.
std::sort requires random access iterators and so cannot be used with list .
In more details it is implemented using hybrid of QuickSort, HeapSort and InsertionSort.By default, it uses QuickSort but if QuickSort is doing unfair partitioning and taking more than N*logN time, it switches to HeapSort and when the array size becomes really small, it switches to InsertionSort.
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.
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, you don’t need to write your own comparer for that, simply use std::greater<T> (located in the standard header <functional>):
Result.poly.sort(std::greater<term>());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With