[英]Custom comparison function for SORT in C++ STL?
I am using 我在用
typedef pair < long , pair <bool ,long > > t;
vector <t> time ;
and I need to sort the above vector using std::sort()
function but using aa customized comparison function. 我需要使用
std::sort()
函数但使用一个自定义的比较函数对上述向量进行std::sort()
。 I wrote a version of it but is not working properly. 我写了一个版本,但是不能正常工作。 Can you please point out my mistake?
你能指出我的错误吗?
bool comp ( const t &a , const t &b){
if ( a.first < b.first)
return a.first > b.first ;
else if ( b.first < a.first )
return b.first > a.first ;
else if ( a.first == b.first )
{
if ( a.second.first == false && b.second.first == true)
return a.first > b.first ;
else if ( a.second.first == true && b.second.first == false)
return b.first > a.first ;
else
return a.first > b.first ;
}
}
inside main(){
sort ( time.begin() ,time.end() ,comp) ;
}
Custom Case: 自定义案例:
Before sorting : vector time 排序前:向量时间
10 1 1
100 0 1
100 1 2
200 0 2
150 1 2
500 0 2
200 1 2
300 0 2
After Sorting: 排序后:
10 1 1
100 0 1
100 1 2
150 1 2
200 0 2
200 1 2
300 0 2
500 0 2
It should be: 它应该是:
if ( a.first < b.first)
return true
else if ( b.first < a.first )
return false;
// etc.
In your version it returns false in both cases. 在您的版本中,两种情况下均返回false。
Your comparison function doesn't define an ordering. 您的比较功能未定义顺序。 In fact, it seems to return true any time
a.first != b.first
. 实际上,似乎任何时候
a.first != b.first
返回true。
I'm not sure what sort of custom order you want. 我不确定您要哪种自定义订单。 The standard ordering of std::pair will result in something like:
std :: pair的标准顺序将导致类似:
bool
comp( t const& a, t const& b )
{
if ( a.first != b.first )
return a.first < b.first;
else if ( a.second.first != b.second.first )
return a.second.first < b.second.first;
else
return a.second.second < b.second.second;
}
It's actually a bit more complicated, since the only comparison operator it uses is <
. 实际上,它有点复杂,因为它使用的唯一比较运算符是
<
。 But if <
and !=
are both available, and behave normally, the results are the same as the above. 但是,如果
<
和!=
都可用,并且行为正常,则结果与上述相同。
You can easily adopt this to compare the elements in whatever order you want; 您可以轻松地采用这种方式以所需的任何顺序比较元素。 if you want to inverse the order for one of the elements, just replace
<
with >
. 如果要反转元素之一的顺序,只需将
<
替换为>
。
And finally, false
compares less than true
for boolean values. 最后,对于布尔值,
false
小于true
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.