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
?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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