为什么是错的
按学生年龄排序。输入n,然后输入n个学生信息(姓名、学号、出生日期年、月、日)按年龄排序(升序)输出。输入
第一行整数n,第2~n+1行的每一行是一个学生的信息:学号、姓名、出生年月日
输出
已按年龄排序的学生信息,每行一个学生
样例输入
4
1002 John 2001 12 25
1001 Mary 2000 10 1
1003 Mark 2001 3 8
1004 Tony 1999 5 13
样例输出
1002 John 2001.12.25
1003 Mark 2001.3.8
1001 Mary 2000.10.1
1004 Tony 1999.5.13
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct birth
{
int y, m, d;
};
struct stu
{
int num;
string name;
birth birth1;
};
int main()
{
int n;
string name1;
cin >> n;
int y, m, d, number;
stu student;
birth birthday;
vector<stu> stus;
for (int i = 0; i < n; i++)
{
cin >> number >> name1 >> y >> m >> d;
birthday.y = y;
birthday.m = m;
birthday.d = d;
student.num = number;
student.name = name1;
student.birth1 = birthday;
stus.push_back(student);
}
for (int i = 0; i < stus.size(); i++)
{
for (int j = 1; j < stus.size(); j++)
{
if (stus.birth1.y < stus.birth1.y)
{
stu temp = stus;
stus = stus;
stus = temp;
}
else if (stus.birth1.y == stus.birth1.y)
{
if (stus.birth1.m < stus.birth1.m)
{
stu temp = stus;
stus = stus;
stus = temp;
}
else if (stus.birth1.m == stus.birth1.m)
{
if (stus.birth1.d < stus.birth1.d)
{
stu temp = stus;
stus = stus;
stus = temp;
}
}
}
}
}
for (int i = 0; i < stus.size(); i++)
{
cout << stus.num << " " << stus.name << " " << stus.birth1.y << "." << stus.birth1.m << "." << stus.birth1.d << endl;
}
return 0;
}
这段代码存在几个问题。首先,它在比较月份和日期时存在逻辑错误。其次,排序算法也有问题。以下是修改后的代码:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct birth {
int y, m, d;
};
struct stu {
int num;
string name;
birth birth1;
};
bool compare(const stu &a, const stu &b) {
if (a.birth1.y != b.birth1.y) {
return a.birth1.y < b.birth1.y;
} else if (a.birth1.m != b.birth1.m) {
return a.birth1.m < b.birth1.m;
} else {
return a.birth1.d < b.birth1.d;
}
}
int main() {
int n;
cin >> n;
vector<stu> stus(n);
for (int i = 0; i < n; i++) {
cin >> stus[ i].num >> stus[ i].name >> stus[ i].birth1.y >> stus[ i].birth1.m >> stus[ i].birth1.d;
}
sort(stus.begin(), stus.end(), compare);
for (int i = 0; i < n; i++) {
cout << stus[ i].num << " " << stus[ i].name << " " << stus[ i].birth1.y << "." << stus[ i].birth1.m << "." << stus[ i].birth1.d << endl;
}
return 0;
}
在这个修改后的代码中,我们引入了一个自定义的比较函数 compare ,并使用 std::sort 函数进行排序。这样可以避免原先代码中存在的逻辑错误,并且使得排序更加简洁和易读。
页:
[1]