Structure Sorting (By Multiple Rules) in C++

Prerequisite : Structures in C

Name and marks in different subjects (physics, chemistry and maths) are given for all students. The task is to compute total marks and ranks of all students. And finally display all students sorted by rank.

Rank of student is computed using below rules.

1. If total marks are different, then students with higher marks gets better rank.
2. If total marks are same, then students with higher marks in Maths gets better rank.
3. If total marks are same and marks in Maths are also same, then students with better marks in Physics gets better rank.
4. If all marks (total, Maths, Physics and Chemistry) are same, then any student can be assigned bedtter rank.

We use below structure to store details of students.

```struct Student
{
string name; // Given
int math;  // Marks in math (Given)
int phy;   // Marks in Physics (Given)
int che;   // Marks in Chemistry (Given)
int total; // Total marks (To be filled)
int rank;  // Rank of student (To be filled)
};
```

We use std::sort() for Structure Sorting. In Structure sorting, all the respective properties possessed by the structure object are sorted on the basis of one (or more) property of the object.

In this example, marks of students in different subjects are provided by user. These marks in individual subjects are added to calculate the total marks of the student, which is then used to sort different students on the basis of their ranks (as explained above).

 `// C++ program to demonstrate structure sorting in C++ ` `#include ` `using` `namespace` `std; ` ` `  `struct` `Student  ` `{ ` `    ``string name; ``// Given ` `    ``int` `math;  ``// Marks in math (Given) ` `    ``int` `phy;   ``// Marks in Physics (Given) ` `    ``int` `che;   ``// Marks in Chemistry (Given) ` `    ``int` `total; ``// Total marks (To be filled) ` `    ``int` `rank;  ``// Rank of student (To be filled) ` `};  ` ` `  `// Function for comparing two students according ` `// to given rules ` `bool` `compareTwoStudents(Student a, Student b) ` `{ ` `    ``// If total marks are not same then ` `    ``// returns true for higher total ` `    ``if` `(a.total != b.total ) ` `        ``return` `a.total > b.total; ` ` `  `    ``// If marks in Maths are not same then ` `    ``// returns true for higher marks ` `    ``if` `(a.math != b.math) ` `            ``return` `a.math > b.math; ` ` `  `    ``return` `(a.phy > b.phy); ` `} ` ` `  `// Fills total marks and ranks of all Students ` `void` `computeRanks(Student a[], ``int` `n) ` `{ ` `    ``// To calculate total marks for all Students ` `    ``for` `(``int` `i=0; i

Output:

```Rank	Name	Maths	Physics	Chemistry	Total
1	Kevin	95	85	99		279
2	Nick	95	85	80		260
3	Bryan	80	95	85		260
4	Howie	80	80	80		240
5	AJ	80	70	90		240
```