我怎么不能按课程代码的降序对数字进行排序



我正在编写一个程序来管理记录列表。用户首先输入多条记录,直到字符串"END"指示输入结束。然后输入学生证并按课程代码降序输出学生的所有记录

我正在尝试使用气泡排序来执行此操作,但我不知道为什么我的程序不起作用。你们能给我任何提示吗?change()功能是将课程代码更改为int而不A

示例输入

SEHH2042 19100001A 76.4 SEHH2042 18001234A 85.2 SEHH2042 19000123A 45.5 SEHH3140 18001234A 89.3 SEHH1034 19100001A 45.7 SEHH1034 18001234A 88.4 SEHH2271 18001234A 85.4 结束 18001234A

样本输出

SEHH3140 89.3 SEHH2271 85.4 SEHH2042 85.2 SEHH1034 88.4
#include <iostream>
using namespace::std;
int change(string id) {
int num;
string dd(id, 4, 7);
num = atoi(dd.c_str());
return num;
}
int main()
{
string subject[1000], x, tmp1;
string id[1000], y, search, tmp2;
double mark[1000], z = 0, sum = 0, tmp3;
int count = 0, flag = 0, id2[100], p = 0, count2 = 0, tmp4;
//input
do {
cin >> x;
if (x == "END") {
flag = 1;
break;
}
cin >> y;
cin >> z;
subject[count] = x;
id[count] = y;
mark[count] = z;
p = change(x);
id2[count] = p;
count++;
} while (flag != 1);
// sort by course code
for (int i = 0; i < count - 1; i++) {
for (int k = count - 1; k > i; k--) {
if (id2[k] > id2[k - 1]) {
tmp1 = subject[k];
tmp2 = id[k];
tmp3 = mark[k];
tmp4 = id2[k];
subject[k] = subject[k - 1];
id[k] = id[k - 1];
mark[k] = mark[k - 1];
id2[k] = id2[k - 1];
subject[k] = tmp1;
id[k] = tmp2;
mark[k] = tmp3;
id2[k] = tmp4;
}
}
}
cin >> search;
// search the result of the student
for (int i = 0; i < count; i++) {
if (search == id[i]) {
cout << subject[i] << " " << mark[i] << endl;
//cout << id2[i]<<endl;
}
}
}

请不要使用并行数组。 您的问题是使用并行数组的复杂性的一个示例。 使用结构集合:

struct Student
{
std::string subject;
std::string id;
double mark;
friend std::istream& operator>>(std::istream& input, Student& s);
};
std::istream& operator>>(std::istream& input, Student& s)
{
input >> s.subject;
input >> s.id;
input >> s.mark;
input.ignore(1000, 'n'); // ignore to the end of the line.
return input;
}
std::vector<Student> database;
Student s;
std::string text_line;
while (std::getline(cin, text_line))
{
if (text_line == "END")
{
break;
}
std::istringstream text_stream(text_line);
text_line >> s;
database.push_back(s);
}

上面的代码在记录中作为结构读取并追加到数据库中。

下面是一个按主题排序的函数:

bool Order_By_Subject(const Student& a, const Student& b)
{
return a.subject < b.subject;
}

按主题排序非常简单:

std::sort(database.begin(), database.end(), Order_By_Subject);

按其他字段(成员(排序可以通过编写附加排序函数并提供给std::sort来完成,如上例所示。

这比使用多个数组要简单得多。

编辑 1:更改排序顺序
可以通过更改比较语句来实现按主题降序排序:

bool Order_Descending_By_Subject(const Student& a, const Student& b)
{
return a.subject > b.subject;
}

然后调用排序函数:

std::sort(database.begin(), database.end(), Order_Descending_By_Subject);

最新更新