在c++中,快排(sort)的cmp函数,返回0和-1有什么区别?
我在做题时,返回0就对了,返回-1就错了。
bool cmp(Student x,Student y){
if(x.year<y.year) return 1;
if(x.year>y.year) return 0;
if(x.year==y.year){
if(x.mon<y.mon) return 1;
if(x.mon>y.mon) return 0;
if(x.mon==y.mon){
if(x.day<y.day) return 1;
if(x.day>y.day) return 0;
if(x.day==y.day){
if(x.num>y.num) return 1;
else return 0;
}
}
}
}
我在做题时把return 0全改成return -1就排错了。
楼主的函数是 bool cmp(Student x,Student y)
, bool
型的值只有 true
和 false
。
这里面 0
是 false
,非 0
值都是 true
,因此:
return 0;
就是 return false;
return -1;
就是 return true;
return 0代表程序的正常退出,为什么要改成return -1没太搞懂
计算机中默认 0为假 非0为真 。若将0改为-1,函数所有返回值均为假,函数的逻辑就错误了。
并且函数返回值应该为bool型变量,建议正规写法 return true or false ,可以提高代码可读性。