29

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?

Jamal
  • 763
  • 7
  • 22
  • 32
Vlad
  • 618
  • 2
  • 10
  • 21
  • @Glen see http://stackoverflow.com/questions/2425452/polynomial-operations-using-operator-overloading – Vlad Mar 12 '10 at 13:25

3 Answers3

44

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.

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
10

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>());
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • No this isn`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 -` is missing for the input iterators. – Andreas Brinck Mar 12 '10 at 13:16
  • It would make a better answer if it was reordered (const-ness is a side-issue here). – visitor Mar 12 '10 at 13:20
  • still doesn't work either with my own comparer or using greater() it still gives a bunch of errors – Vlad Mar 12 '10 at 13:21
  • @Andreas: my concern was that a temporary object gets passed into the `sort` function. I had forgotten that the comparer is passed by value and since temporaries cannot be bound to non-`const` references this would have required the function to be `const`. – Konrad Rudolph Mar 12 '10 at 13:25
  • @Vlad: *what* errors? This code should work. Did you include the header `` for `std::greater`? – Konrad Rudolph Mar 12 '10 at 13:26
  • 1
    `std::greater` will only work if `operator>` is overloaded for `term` which probably isn't the case here. – UncleBens Mar 12 '10 at 16:36
4

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

Andreas Brinck
  • 51,293
  • 14
  • 84
  • 114