[英]Overloading “ < ” for STL sort()
我制作了一個結構,其中包含兩個均為long long int類型的變量,例如x
和y
。
我可以通過重載<
運算符並基於任何一個變量進行sort()
來使用STL sort()
。
struct point
{
long long int x, y;
};
bool compare(point lhs, point rhs)
{
return lhs.x < rhs.x;
}
sort(point, point + t, compare);
我想做的是基於x
對結構進行排序,但是當兩個存儲桶的x
值相同時,應首先放置y
值較小的存儲桶。 我該如何實現?
比較x
和y
的元組:
bool compare(point lhs, point rhs)
{
return std::tie(lhs.x, lhs.y) < std::tie(rhs.x, rhs.y);
}
這正是您想要的。
std::tie
參考頁甚至提供了與您所做的基本上相同的示例。
這就是您所說的:
bool compare(point lhs, point rhs)
{
return (lhs.x == rhs.x)
? (lhs.y < rhs.y)
: (lhs.x < rhs.x);
}
另外, std::sort()
的比較器應采用const lvalue-references:
bool compare(point const& lhs, point const& rhs);
inline bool compare(const point& lhs, const point& rhs)
{
if (lhs.x < rhs.x)
return true;
if (lhs.x > rhs.x)
return false;
return lhs.y < rhs.y;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.