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?
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?
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;
});
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);
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);
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);
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.