I understand you can insert a user-defined class in to a std::vector
and then overload the sorting mechanism so that it compares on a particular data member. However, how would you sort a std::vector<MyClass>
where MyClass
has two data members and you want to add a "second level" of sorting on the second data member? So sort on data member a
and where a
is equal, then sort on data member b
?
Create a custom comparator using std::tuple
#include <tuple>
//..
struct comp
{
bool operator()(const MyClass& lhs, const MyClass& rhs) const
{
return std::tie(lhs.a, lhs.b) < std::tie(rhs.a, rhs.b);
}
};
It will use a
first and then b
second
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