leetcode刷题中cmp用<可以而 -不行,有什么区别吗
//这个为啥不行啊leetcode905把偶数排前面
class Solution {
public:
static int cmp (int a, int b) {
return a%2-b%2;
}
vector<int> sortArrayByParity(vector<int>& a) {
sort (a.begin(), a.end(), cmp);
return a;
}
};
首先用 <
绝对正确,也符合 std::sort
的参数要求。如果用 -
,由于 std::sort
第三个参数是一个返回值为 bool
的函数,当这个函数返回值为 True
的时候,表示第一个数应该在第二个数前面,而 bool
类型的如果从 int
类型转换,会导致除了 0
以外的全部变为 True
。考虑下面情况,a%2==1
,b%2==0
,则在 <
写法中返回 false
,而在 -
写法中返回 -1
,被转为 true
,明显结果不符合。
这两个表达式代表的意思都不一样吧,你改的那个是解答错误,意思就是结果错了。
bool类型中0为false非0为true,用int转换为bool时c++中cmp的sort看0 1,c语言中cmp的qsort看正负