本文共 2983 字,大约阅读时间需要 9 分钟。
字符串比较函数的实现是一个常见但容易出错的编程任务。在C++编程中,用户曾遇到过一个类似的问题,即自定义的字符串比较函数无法正确排序字符串,导致程序逻辑错误。通过分析错误代码以及参考相关资料,最终找到了正确的实现方法,并总结了几个值得注意的点。
#include#include #include #include using namespace std;struct str{ char s[16]; int index;};bool cmp(str a, str b){ int len1 = strlen(a.s); int len2 = strlen(b.s); if (len1 == 0 || len2 == 0) return false; int k = 0; while (k < len1 && k < len2) { if (a.s[k] != b.s[k]) return a.s[k] < b.s[k]; k++; } if (len1 == len2) return true; int temp = 0; while (k < len1) { if (b.s[temp % len2] != a.s[k]) return a.s[k] < b.s[temp % len2]; temp++; k++; } while (k < len2) { if (b.s[k] != a.s[temp % len1]) return a.s[temp % len1] < b.s[k]; temp++; k++; } return len1 > len2;}bool test(char *a, char *b){ if (strlen(a) == 0) { if (b[0] == '0' && strlen(b) == 1) return false; if (b[0] == '0') { strcpy(a, b + 1); } else { strcpy(a, b); } return true; } else { str a_temp, b_temp; strcpy(a_temp.s, a); strcpy(b_temp.s, b); if (a[0] == '0') { strcpy(a_temp.s, a + 1); } if (b[0] == '0') { strcpy(b_temp.s, b + 1); } if (cmp(b_temp, a_temp)) { strcpy(a, b_temp.s); return true; } return false; }}int main(){ vector vec, vec_non_zero; int n, _min = 1e9, index; str temp; char ch[16]; ch[0] = '\0'; cin >> n; for (int i = 0; i < n; i++) { cin >> temp.s; temp.index = i; vec.push_back(temp); if (test(ch, temp.s)) { index = i; } } sort(vec.begin(), vec.end(), cmp); cout << ch; for (int i = 0; i < vec.size(); i++) { if (vec[i].index == index) continue; cout << vec[i].s; }}
比较逻辑不够完善
错误的cmp函数没有正确处理不同长度的字符串,导致排序结果不符合预期。特别是在字符串长度不同时,函数可能会出现意外的比较结果。递归或循环逻辑错误
代码中包含了一些复杂的递归或循环逻辑,容易出错。例如,temp变量的使用和字符串的拼接操作可能会导致意外情况。缺乏测试和验证
在test函数中,字符串的处理逻辑较为复杂,尤其是在处理带有前导零的字符串时,容易出错。缺乏充分的测试案例导致问题难以发现。#include#include #include #include #include using namespace std;vector temp;bool cmp(string a, string b){ return a + b < b + a;}int main(){ int num, i; string str, tes; cin >> num; for (i = 0; i < num; i++) { cin >> str; temp.push_back(str); } sort(temp.begin(), temp.end(), cmp); for (int i = 0; i < temp.size(); i++) { cout << temp[i] << endl; }}
简化比较逻辑
正确的cmp函数采用了更简洁的方式进行字符串比较,直接比较a + b和b + a的大小,避免了复杂的循环逻辑。处理字符串拼接
在test函数中,字符串的拼接操作更加简单直接,避免了不必要的复杂操作。优化性能
删除了不必要的递归和循环结构,使代码运行更加高效。在编写自定义的字符串比较函数时,建议采用简洁的方式处理字符串拼接和比较逻辑。通过直接比较a + b和b + a的大小,可以有效地解决字符串排序问题,同时避免复杂的递归或循环逻辑。
转载地址:http://rxvfk.baihongyu.com/