0

我正在学习 c++,我被赋予了任务。我需要创建结构Student

#include "stdafx.h"
using namespace std;

const int num = 5;

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

并与之合作。
这是我的程序

#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

2 回答 2

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);
于 2013-10-11T13:19:42.023 回答
1
    vector<Student> students(n);
    .. populate students
    sort(students.begin(), students.end(), [](const Student& left, const Student& right){ return left.groupNumber < right.groupNumber; });
于 2013-10-11T13:21:50.013 回答