问题描述
我对编码还是比较陌生,最近的一个任务让我很困惑。
我有两个基本上相互链接的数组。一侧的 0 必须是另一侧的 0,我需要找到最简单的方法将数字按降序排序,同时对另一侧进行同样的操作。
int main()
{
/// Declare Variables
int studentNum,j;
int studentGrade[20];
string studentName[20];
/// Prompt the user for the number of loops that will be required
cout << "How many students are in the class? ";
cin >> studentNum;
cout << endl;
/// Enter a for loop
for(int i=0;i<studentNum;i++)
{
/// Prompt the user to enter the names of each student in the array,as well as their respective grade.
cout << "Enter the student's name: ";
cin >> studentName[i];
cout << "Enter the student's grade (0-100): ";
cin >> studentGrade[i];
}
cout << endl << endl;
cout << setw(25) << left << "Student's Name" << setw(25)<< "Test Score" << endl;
///********Sorting block required*********
/// Enter another for loop,this time to show the array to the screen
for (int i=0;i<studentNum;i++)
{
cout << setw(25) << studentName[i] << setw(25) << studentGrade[i] << endl;
}
return 0;
}
我已经尽可能多地查找了这个问题的答案,但一直没有找到适合我的答案。有人知道我可以在这里做什么吗?我必须将它们保留为两个单独的数组。如果可能,我也想尝试不使用 sort()。
解决方法
您选择哪种排序算法并不重要,您只需要遍历其中一个数组,每当您更改一个单元格的索引时,您都会将其更改为另一个数组中的相同单元格索引
例如:
for (int i = 0; i < size; i++){
if(arr[i]<arr[i+1]){
temp=arr[i];
temp2=arr2[i];
arr[i]=arr[i+1];
arr2[i]=arr2[i+1];
arr[i+1]=temp;
arr2[i+1]=temp2;
}
}
,
您可以在双循环中像这样对数组进行排序:
for(int j=0 ; j<studentNum ; j++)
for(int i=0 ; i<studentNum-1 ; i++){
if(studentGrade[i] < studentGrade[i+1]){ //swapping condition
string temp = studentName[i];
studentName[i] = studentName[i+1];
studentName[i+1] = temp;
int x = studentGrade[i];
studentGrade[i] = studentGrade[i+1];
studentGrade[i+1] = x;
}
}
如果数组中一个学生的成绩低于数组中他旁边学生的成绩,那么你可以交换他们,也可以分别交换他们的名字
,使用 C++ STL 约定,vector
、pair
和 sort
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
vector<pair<string,int> > students;
cin >> n;
// Input name and grade of all students
while (n--) {
string name;
int grade;
cin >> name >> grade;
students.push_back(make_pair(name,grade));
}
// Sort students based on their grades descending
sort(students.begin(),students.end(),[](const auto & a,const auto & b) -> bool {
return a.second > b.second;
});
// Output students' name and grade
for (auto & s : students) {
cout << setw(25) << s.first << setw(25) << s.second << endl;
}
return 0;
}