C++ Record类对象数组按日期升序排序失效问题排查
日期排序失效的排查与修正
问题根因
- 最直接的致命错误:
sortByDate函数内的if判断行末尾多写了一个分号
原代码片段:
C++语法会把这个分号解析成一个空语句,直接终止if的作用范围。后续大括号包裹的交换代码不再受判断条件控制,每轮循环不管相邻元素的日期对比结果如何,都会强制交换位置,直接打乱数组原有顺序,根本无法实现按条件排序的效果。if (isGreater(arr[j], arr[j+1])); //{4.20, 3.15, 5.21, 6.21, 6.20} { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } - 逻辑匹配核对:你当前写的
isGreater函数逻辑是当r1的日期晚于r2时返回true,搭配冒泡排序里“条件为真就交换相邻元素”的规则,正好符合日期升序的排序要求,不需要额外调整判断分支的方向。你最初设计描述里提到的“r1小于r2就返回true”的思路和实际写的代码逻辑有出入,但实际落地的判断逻辑是适配当前排序流程的。
修正操作
- 删掉
sortByDate函数中if语句后面多余的分号 - 可选优化:给类中的getter函数加上const修饰,保证const类对象也能正常调用成员访问接口
修正后的完整可运行代码
#include <iostream> using namespace std; class Record { private: int month, day; double balance; public: void set(int m, int d, double b) { month = m; day = d; balance = b; } int getMonth() const { return month; } int getDay() const { return day; } double getBalance() const { return balance; } }; bool isGreater(Record r1, Record r2) { if (r1.getMonth() > r2.getMonth()) { return true; } else if (r1.getMonth() < r2.getMonth()) { return false; } else { if (r1.getDay() > r2.getDay()) { return true; } else { return false; } } } void sortByBalance(Record arr[], int n) { int i, j; Record temp; for (i = 0; i < n - 1; i++) { for (j = 0; j < n - i - 1; j++) { if (arr[j].getBalance() > arr[j + 1].getBalance()) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } void sortByDate(Record arr[], int n) { int i, j; Record temp; for (i = 0; i < n - 1; i++) { for (j = 0; j < n - i - 1; j++) { // 移除原代码中if后多余的分号 if (isGreater(arr[j], arr[j+1])) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } void printArr(Record arr[], int n) { for (int j = 0; j < n; j++) { cout << arr[j].getMonth() << ' ' << arr[j].getDay() << ' ' << arr[j].getBalance() << endl; } } int main() { Record arr[30]; int n; cout << "Enter the number of the records:" << endl; cin >> n; cout << "Enter the contents of each records:" << endl; int m, d; double b; for (int i = 0; i < n; i++) { cin >> m >> d >> b; arr[i].set(m, d, b); } cout << "sorting according to balance:" << endl; sortByBalance(arr, n); printArr(arr, n); cout << "\nsorting according to date:" << endl; sortByDate(arr, n); printArr(arr, n); }
效果验证
输入对应3条测试记录:
3 9 14 -104.6 12 14 -104.5 12 13 -104.5
输出结果和预期完全匹配:
sorting according to balance: 9 14 -104.6 12 14 -104.5 12 13 -104.5 sorting according to date: 9 14 -104.6 12 13 -104.5 12 14 -104.5
内容的提问来源于stack exchange,提问作者cheng raphael
相关产品推荐
相关产品推荐

