Reputation: 26387
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
?
Upvotes: 18
Views: 51330
Reputation: 36049
std::list<T>::sort
has a one-argument form, with the first argument being the comparison function.
Upvotes: 4
Reputation: 15934
You can do something like this:
typedef std::pair<int,int>;
list<my_type> test_list;
bool my_compare (my_type a, my_type b)
{
return a.first < b.first;
}
test_list.sort(my_compare);
If the type was a struct or class it would work something like this:
struct some_struct{
int first;
int second;
};
list<some_struct> test_list;
bool my_compare (const some_struct& a,const some_struct& b)
{
return a.first < b.first;
}
test_list.sort(my_compare);
Or alternatively you can define operator <
for your struct and just call test_list.sort()
Upvotes: 3
Reputation: 477040
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.
Upvotes: 35