[英]Sorting two arrays that are linked into descending order. One is a string array, one is an int array. c++
我对编码还是比较陌生,最近的一项任务让我很难过。
我有两个基本上相互链接的数组。 一侧的 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;
}
}
您可以在 double for 循环中对这样的数组进行排序:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.