Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a list of a custom type

Tags:

c++

stl

I want to have a stl list of objects where each object contains two int's. Afterwards I want to sort the list with stl::sort after the value of the first int. How do I tell the sort function that it's supposed to sort after the first int?

like image 392
Christian Avatar asked Nov 14 '11 12:11

Christian


People also ask

Can we sort data using custom list?

You can also create your own custom list, and use them to sort or fill. For example, if you want to sort or fill by the following lists, you'll need to create a custom list, since there is no natural order. A custom list can correspond to a cell range, or you can enter the list in the Custom Lists dialog box.

How do you sort a custom list in Python?

Custom Sorting With key= The key function takes in 1 value and returns 1 value, and the returned "proxy" value is used for the comparisons within the sort. For example with a list of strings, specifying key=len (the built in len() function) sorts the strings by length, from shortest to longest.


2 Answers

You can specify a custom sort predicate. In C++11 this is best done with a lambda:

typedef std::pair<int, int> ipair;
std::list<ipair> thelist;

thelist.sort([](const ipair & a, const ipair & b) { return a.first < b.first; });

In older versions of C++ you have to write an appropriate function:

bool compFirst(const ipair & a, const ipair & b) { return a.first < b.first; }

thelist.sort(compFirst);

(Instead if ipair you can of course have your own data structure; just modify the comparison function accordingly to access the relevant data member.)

Finally, if this makes sense, you can also equip your custom class with an operator<. That allows you to use the class freely in any ordered context, but be sure to understand the consequences of that.

like image 189
Kerrek SB Avatar answered Oct 11 '22 10:10

Kerrek SB


std::list<T>::sort has a one-argument form, with the first argument being the comparison function.

like image 36
thiton Avatar answered Oct 11 '22 11:10

thiton