簡體   English   中英

為STL sort()重載“ <”

[英]Overloading “ < ” for STL sort()

我制作了一個結構,其中包含兩個均為long long int類型的變量,例如xy

我可以通過重載<運算符並基於任何一個變量進行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值較小的存儲桶。 我該如何實現?

比較xy的元組:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM