1

How can I sort a list of classes by a certain member variable?

class Klasse {
  int _a;
  int _b;

}

...
list<Klasse> liste;
liste.sort();   // sorts by _a
liste.sort(?);  // how to sort by _b now?
j08691
  • 204,283
  • 31
  • 260
  • 272
SimonH
  • 1,385
  • 15
  • 35
  • Have you tried [creating a custom comparator](http://stackoverflow.com/questions/12508496/comparators-in-stl)? – tadman Jan 14 '15 at 18:00

5 Answers5

4

You would use a comparator object. Here's an example using a lambda.

std::list<Klasse> liste;
liste.sort([](Klasse const & lhs, Klasse const & rhs) {
    return lhs._b < rhs._b;
});
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
3

See the reference.

You can write a comparison function - basically anything that can be called with two arguments of the element type of your list, and this call returns value convertible to bool. Such "anything" can be a lambda, function object, or simply just a function:

bool klasse_sort_by_b(const Klasse& l, const Klasse& r)
{
    return l._b < r._b;
}

liste.sort(klasse_sort_by_b);
milleniumbug
  • 15,379
  • 3
  • 47
  • 71
1

you need this implementation of sort:

template<typename Compare>    
void sort (Compare comp);

then pass inside a compare function like:

bool compareByA( const Klasse& first, const Klasse& second ){
 return first._a < second._a;
}

then call it:

std::list<Klasse> lst;
...
lst.sort(compareByA);
lst.sort(compareByB);
AlexTheo
  • 4,004
  • 1
  • 21
  • 35
0

http://www.cplusplus.com/reference/list/list/sort/

You should write your own comparer, example and usage in the link ;)

here is the code example as promised

(thanks for the constructive criticism)

 bool compare_by_b (const Klasse& first, const Klasse& second)
    {
      return first._b < second._b ;
    }

 liste.sort(compare_by_b);
Zongor Lajos
  • 37
  • 1
  • 3
  • You should include code in your answer instead of linking to external resources. – Overv Jan 14 '15 at 18:01
  • 2
    he answers the question (though shortly), and gives a reference. Possibly not the most thorough explanation, but worth more than a downvote! – Marcus Müller Jan 14 '15 at 18:02
  • @MarcusMüller: http://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers – Bill Lynch Jan 14 '15 at 18:05
  • I agree, but he did *not* just link somewhere. He said "write a comparer", which is absolutely true and might even be enough to give OP a start, if the linked site went down at one point. – Marcus Müller Jan 14 '15 at 18:09
-1

Yes, and all you have to do is implement a comparator class, or overload the comparison Klasse::operator< operators. For reference on the sort method, see this.

Marcus Müller
  • 34,677
  • 4
  • 53
  • 94