Read n students (name and CGPA) and print them from the highest CGPA to the lowest. Students with the same CGPA are printed in dictionary order of their names. Use sort with a comparison function.
What to build
A program that sorts students with sort and a comparison function.
Requirements
- Store the students in a
vector. - Order by CGPA from highest to lowest, and by name when the CGPAs are equal.
- Print each CGPA with two decimals.
Input
The first line has n (1 ≤ n ≤ 100). Each of the next n lines has a name (one word) and a CGPA.
Output
n lines: NAME CGPA, with the CGPA to two decimals.
Constraints
1 ≤ n ≤ 100, and names are one word.
Example
Input:
3
Rahim 3.5
Nadia 3.92
Karim 3.5
Output:
Nadia 3.92
Karim 3.50
Rahim 3.50
Why it works
sort only needs to know which of two students should come first. The comparison function answers exactly that, so the whole list ends up in the right order.
Examples
3 Rahim 3.5 Nadia 3.92 Karim 3.5
Nadia 3.92 Karim 3.50 Rahim 3.50
1 Solo 4
Solo 4.00
Hints
Hint 1
Store the students in a vector<Student>.
Hint 2
Write bool better(const Student& a, const Student& b): higher cgpa first; on a tie, the name that comes first.
Hint 3
sort(list.begin(), list.end(), better); then print with fixed and setprecision(2).
Solution
Show one correct solution (try it yourself first)
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct Student {
string name;
double cgpa;
};
bool better(const Student& a, const Student& b) {
if (a.cgpa != b.cgpa) return a.cgpa > b.cgpa;
return a.name < b.name;
}
int main() {
int n;
cin >> n;
vector<Student> list(n);
for (int i = 0; i < n; i++) cin >> list[i].name >> list[i].cgpa;
sort(list.begin(), list.end(), better);
cout << fixed << setprecision(2);
for (const Student& s : list) cout << s.name << " " << s.cgpa << endl;
return 0;
}
Lesson: The standard library: vector, string, map and sort →