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
?
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.
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.
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.
std::list<T>::sort
has a one-argument form, with the first argument being the comparison function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With