Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list using STL sort function

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?

like image 746
Vlad Avatar asked Mar 12 '10 13:03

Vlad


People also ask

How do I sort a list in CPP STL?

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.

Can you use std::sort with a list?

std::sort requires random access iterators and so cannot be used with list .

Which sorting is used in STL sort?

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.


2 Answers

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.

like image 183
David Rodríguez - dribeas Avatar answered Oct 08 '22 10:10

David Rodríguez - dribeas


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>()); 
like image 42
Konrad Rudolph Avatar answered Oct 08 '22 09:10

Konrad Rudolph