How can I compare/sort elements of a list container containing a custom typedef?
c++, compare, containers, list, stl
Solution
You can use `std::list::sort` with a custom comparison function:
inline bool comp(const weightedVariable& lhs, const weightedVariable& rhs)
{
return lhs.second < rhs.second;
}
tmp.sort(comp);
Another option is to provide a `bool operator<` and use `std::list::sort()`:
inline bool operator < (const weightedVariable& lhs, const weightedVariable& rhs)
{
return lhs.second < rhs.second;
}
tmp.sort();
Problem
I want to use the `std::list` STL container to be able to apply an order on the items contained. However, the items I want to use are a custom `typedef` consisting of a custom type and a `double` which represents a weight. How can I make sure that I can sort the resulting list based on the weight of the elements? ``` typedef std::pair<linearVariable*, double> weightedVariable; ``` [...] ``` std::list<weightedVariable> tmp; ``` What do I have to do to make sure that the list is sorted according to the second part of the pair (the weight)? Is there any better way to maintain an order of custom types? In my case the weight is not a property of the `linearVariable`, but it can be calculated.