Sorting Help

I need to take my code here and in the output report sort it so its the people with the highest averages at the top and the people with the lowest averages at the bottom. How do I do this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
#include <ctime>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

struct Grade
{
	std::string last,
		first,
		middle,
		absence;
	double test1,
		   test2,
		   test3;


	friend std::istream &operator>>(std::istream &in, Grade &s)
	{
		return in >> s.last >> s.first >> s.middle >> s.test1 >> s.test2 >> s.test3 >> s.absence;
	}
	friend std::ostream &operator<<(std::ostream &out, const Grade &s)
	{
		return out << "Name: "      << s.first << " "    << s.middle << " " << s.last      << std::endl
			<< "Test Average: "  << (s.test1+s.test2+s.test3)/3  << std::endl
			<< "Absences: "  << s.absence  << std::endl;
	}
};


void main ()
{
	std::vector<Grade> grades;

	{
		std::ifstream infile ("students.txt");
		Grade temp;
		while(infile >> temp)
		{
			grades.push_back(temp);
		}
	}

	for(size_t i = 0; i < grades.size(); ++i)
	{
		std::cout << grades[i] << std::endl;
	}
}
I'd start with creating an average variable, it'll be easier to keep track of your tests.. Also, create an array for the tests of the students.

double Avg = (s.test1+s.test2+s.test3)/3;

That way when you create the oh so needed for loop, you can have a fun time..
double testAvg[numOfAverages]={(Input here the instructions for getting test averages)}
1
2
3
4
5
for (int x = 0; x < numOfAverages; x++){
              if(testAvg[x]>testAvg[0]){
                      testAvg[0] = testAvg[x]
                           }
                     }


I know it's not much, but it'll simplify what the more experienced coder after me will have to say.

I'm a very beginner programmer, and your code looks way too foreign to me at my current state.. Haven't had much play with std:: but it looks to be another way of creating a sort of class maybe? Not sure.. Anyway, no bashing please, only giving as much input as I can.
Last edited on
I'm pretty new to. Where would I even put those 2 segments of code?
Not sure why you'd name the two overloaded operators as friend function since they are actually member functions. Not only that, structs have public default access, so they don't need private member access anyway.
Topic archived. No new replies allowed.