用C ++实现数组

时间:2013-06-14 03:46:42

标签: c++

我有2个数组 一个阵列由学生组成 第二个数组包含为这些学生生成的随机成绩。如何编写这些数组,以便我可以使用冒泡排序按等级的降序对这些数组进行排序?

students[i] = i # 0f students 
Grade1[i] = rand()%91+10 ; // score for exam 1,I did not write the loop which generates random numbers

我怎样才能将这两者放在一起所以我可以通过参考等级进行排序..从最高等级到最高等级

3 个答案:

答案 0 :(得分:1)

我想您想将2 single-Dimensional arraysN元素分别放入2D arrayN行和2列,然后以下代码可能很有用。

int arr[100][2];

cout<<"\n Enter the Number of students: ";
cin>>n;

for(int i=0; i<n; i++)
{
  arr[i][0]=students[i];
  arr[i][1]=Grade1[i];
}

// Now use bubble sort to sort the second column of array arr

for(int i=0; i<n; i++)
{
   for(int j=i; j<n; j++)
   {
      if(arr[i][1] < arr[j][1])
      {
         int t1;
         t1=arr[i][1];
         arr[i][1]=arr[j][1];
         arr[j][1]=t1;
         t1=arr[i][0];
         arr[i][0]=arr[j][0];
         arr[j][0]=t1;

      }      
   }
} 

答案 1 :(得分:1)

从冒泡排序的简单实现开始(例如:take a look at pseudocode available on Wikipedia),然后使用学生成绩来比较排序

您可以像这样存储学生和成绩。等级数组的第n个元素代表第n个学生的等级

int studentIds[10];
int grade[10];

在你的冒泡排序中,使用类似下面的条件来比较学生根据他/她的成绩

// iterate students using two indices i & j
...
if(grade[i] < grade[j]) {
  // .. bubble element i to the right
}
...

答案 2 :(得分:1)

如果你可以使用现代的c ++工具,比如std::vector和其他很酷的商业工具,比如std::sort(对std::vector进行排序),那么它比使用原始数组做得更干净得多。学习使用容器类和语言的内置算法将很好地为您服务。

#include <vector>
#include <algorithm>
#include <iostream>
struct Student //structure to hold student ID and grade info
{
    Student(int id, int grade):id(id),grade(grade){}
    int id;
    int grade;
};
//comparison operator to use with std::sort
bool operator <(const Student& lhs, const Student& rhs)
{
    return lhs.grade < rhs.grade;
}
int main()
{
    //You are starting with raw arrays...
    int studentID[5]{1,2,3,4,5};
    int grade[5]{90,91,73,62,87};

    //convert to std::vector of Student objects
    //not safe indexing into raw array, just an example
    std::vector<Student> students;
    for(unsigned int i=0;i<5;++i){
        students.push_back(Student(studentID[i],grade[i]));}

    //sort the vector (using the less-than operator provided above)
    std::sort(students.begin(),students.end());
    //reverse the vector, making it high-to-low order
    std::reverse(students.begin(),students.end());

    //print the result (uses std::for_each with a lambda function)
    std::for_each(students.begin(),students.end(),
    [](Student s){std::cout<<"ID: "<<s.id<<" grade: "<<s.grade<<std::endl;});
}

输出:

ID: 2 grade: 91
ID: 1 grade: 90
ID: 5 grade: 87
ID: 3 grade: 73
ID: 4 grade: 62