题目:输入任意(用户,成绩)序列,可以获得成绩从高到低或从低到高的排列,相同成绩 示例: 从高到低 成绩 从低到高 smith 67 jack 70 输入描述:
输出描述:
//在C中定义一个结构体类型要用typedef: typedef struct Student{ int a; }Stu; 于是在声明变量的时候就可:Stu stu1;(如果没有typedef就必须用struct Student stu1; // 但在c++里很简单,直接 struct Student { int a; }; 于是就定义了结构体类型Student,声明变量时直接Student stu2; // #include <iostream> #include <string> #include <vector> using namespace std; typedef struct student { string name; int score; }student; int n; void sort(vector<student>& s, int k); int main() { int k; cin >> n >> k;//输入录用人数和排序方式,0降序,1升序 vector<student> s;//vector向量容器,存放student类型 //成绩录入 int i = 0; student temp; for (i = 0; i < n; i++) { cin >> temp.name >> temp.score; s.push_back(temp); } sort(s, k);//排序 //打印输出排序后的成绩 for (i = 0; i < n; i++) { cout << s[i].name << " " << s[i].score << endl; } system("pause"); return 0; } void sort(vector<student>& s, int k) { int i = 0, j = 0; string tempStr; int tempscore; for (i = 0; i < n - 1; i++) { for (j = 0; j < n - 1 - i; j++) { if (0 == k) { if (s[j].score < s[j + 1].score) { tempscore = s[j + 1].score; s[j + 1].score = s[j].score; s[j].score = tempscore; tempStr = s[j].name; s[j].name = s[j + 1].name; s[j + 1].name = tempStr; } } else { if (s[j].score > s[j + 1].score) { tempscore = s[j].score; s[j].score = s[j + 1].score; s[j + 1].score = tempscore; tempStr = s[j].name; s[j].name = s[j + 1].name; s[j + 1].name = tempStr; } } } } } //////////////////////////////////// #include<iostream> #include<vector> #include<string> using namespace std; class student { public: string name ; int score ; }; int n; void sort(vector<student>&s, int k); int main() { cout << "please input students number n="; cin >> n; cout << "选择排序方法,1升0降,k="; int k; cin >> k; cout << "输入学生成绩和名字" << endl; vector<student> s; student temp; for (int i = 0; i < n; i++) { cin >> temp.name >> temp.score; s.push_back(temp); } /* for (int i = 0; i < n; i++) { cout << s[i].name << " " << s[i].score << endl; } */ cout << "开始排序" << endl; sort(s, k); for (int i = 0; i < n; i++) { cout << s[i].name << " " << s[i].score << endl; } /* please input students number n=4 选择排序方法,1升0降,k=1 输入学生成绩和名字 黄俊木 60 夏宇 89 周思寒 99 黄明敏 60 开始排序 黄俊木 60 黄明敏 60 夏宇 89 周思寒 99 请按任意键继续. . . */ system("pause"); } void sort(vector<student>&s, int k) { string tempname; int tempscore; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - 1 - i; j++) { if (0==k) { if (s[j].score < s[j + 1].score) { tempscore = s[j].score; s[j].score= s[j+1].score; s[j + 1].score = tempscore; tempname = s[j].name; s[j].name = s[j+1].name; s[j + 1].name = tempname; } } else { if (s[j].score > s[j + 1].score) { tempscore = s[j+1].score; s[j+1].score = s[j].score; s[j ].score = tempscore; tempname = s[j + 1].name; s[j + 1].name = s[j].name; s[j].name = tempname; } } } } } 1
|
|