Reputation: 3254
I'm studying c++ and I was given the task. I need to created structure Student
#include "stdafx.h"
using namespace std;
const int num = 5;
struct Student {
string name;
int groupNumber;
int progress[num];
};
and work with it.
it's my 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;
}
I need to sort students in accordance with the growth of groupNumber.
I tried to use pointers but it works wrong. How to make the sorting works the right way?
Upvotes: 0
Views: 121
Reputation: 21773
vector<Student> students(n);
.. populate students
sort(students.begin(), students.end(), [](const Student& left, const Student& right){ return left.groupNumber < right.groupNumber; });
Upvotes: 1
Reputation: 57688
A possibility is to use std::sort
with a comparator method on your array.
Example:
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);
Upvotes: 3