2013-10-11 145 views
0

我正在学习C++,我被赋予了任务。我需要创建结构Student对结构数组进行排序

#include "stdafx.h" 
using namespace std; 

const int num = 5; 

struct Student { 
    string name; 
    int groupNumber; 
    int progress[num]; 
}; 

并与它一起工作。
这是我PROGRAMM

#include "stdafx.h" 
#include "Student.h" 
using namespace std; 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
srand((unsigned)time(NULL)); 

int n; 
cout << "Input n = "; 
cin >> n; 
cin.ignore(); 

Student * Group = new Student[n]; 

for (int i = 0; i < n; ++i) 
{ 
    cout << "Input name: "; 
    getline (cin, Group[i].name); 
    Group[i].groupNumber = rand()%5 + 1; 
    for (int j = 0; j < num; ++j) 
    { 
     Group[i].progress[j] = rand()%5 + 2; 
    } 
} 

int * groupNumberArray = new int[n]; 
for (int i = 0; i < n; ++i) 
{ 
    groupNumberArray[i] = Group[i].groupNumber; 
} 

for (int i; i < n - 1; ++i) 
{ 
    int min = i; 
    for (int j = i + 1; j < n; ++j) 
    { 
     if (groupNumberArray[min] <= groupNumberArray[j]) continue; 
     min = j; 
    } 
    if (min != i) 
    { 
     int temp = groupNumberArray[i]; 
     groupNumberArray[i] = groupNumberArray[min]; 
     groupNumberArray[min] = temp; 

     Student * tempStudent = &Group[i]; 
     &Group[min] = &Group[i]; 
     &Group[i] = tempStudent; 
    } 
} 

cout << "\n\n"; 

delete [] Group; 
delete [] groupNumberArray; 

system("PAUSE"); 
return 0; 
} 

我需要按照groupNumber的生长学生进行排序。
我试图使用指针,但它的工作原理错误。如何使分拣工作正确?

+4

请注明您的要求,否则我们只会说: “用'的std :: sort'用合适的谓词,结束”。 – juanchopanza

+1

C++的方法是:为Student结构提供一个比较器,并使用排序算法。 – dornhege

+2

声明'组'作为'std :: vector 组;然后使用'std :: sort' .... –

回答

3

一种可能性是在您的阵列上使用std::sort与比较器方法。

例子:

bool Compare_By_Group(const Student& a, const Student& b) 
{ 
    return a.groupNumber /* insert comparison operator here */ b.groupNumber; 
} 

// The sort function call 
    std::sort(&Group[0], 
       &Group[/* last index + 1*/], 
       Compare_By_Group); 
+0

'&Group [/ * last index + 1 * /]'是非法的C++(UB)。除了重载分辨率的原因外,使用'Group + N'(真的没有理由使用'&Group [0]'代替'Group'的指针衰减)。 –

1
vector<Student> students(n); 
    .. populate students 
    sort(students.begin(), students.end(), [](const Student& left, const Student& right){ return left.groupNumber < right.groupNumber; });