之前遇到字典序排序的问题,一时间没能想出来,之后想好后记录下来。
问题描述:给出一个字符串,是一个不是多个string,有大写有小写,排序结果为AaBbCcDd......
之前一直不明白sort函数的自定义函数的工作原理,现在搞懂了。
bool cmp1(char &a, char &b) //返回false调换
{
if ((islower(a) && islower(b)) || (isupper(a) && isupper(b)))
return int(a) < int(b);
else if (islower(a) && isupper(b))
{
if (int(a) - int(b) == 32)
return false;
else
return int(a) - 32 < int(b);
}
else
{
if (int(a) - int(b) == -32)
return true;
else
return int(a) < int(b) - 32;
}
}
自定义比较函数的两个输入a和b看成序列的前一个和后一个,经过计算,如果函数返回false就将这两个调换位置,说到这里还是不是非常清楚。其实不管是降序还是升序,a和b都是前后元素,如果符合规则就返回true不调换,否则返回false。
bool cmp1(int &a, int &b)
{
if (a >= b)//降序
return true;
else
return false;
}
bool cmp1(int &a, int &b)
{
if (a <= b)//升序
return true;
else
return false;
}