You do not need to write a sorting algorithm — C++ ships one, and it is faster than anything you would write. What you need to know is how to call it, and how to give it your own rule.
ON THIS PAGE
SHOW EXAMPLE IN
//THE EXAMPLE
main.cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Student {
string name;
int score;
};
bool byScore(const Student& a, const Student& b) {
return a.score > b.score;
}
int main() {
vector<int> v = {5, 2, 9, 1};
sort(v.begin(), v.end());
for (int x : v) cout << x << " ";
cout << endl;
vector<Student> s = {{"Bat", 70}, {"Suvd", 95}, {"Tuul", 82}};
sort(s.begin(), s.end(), byScore);
for (const Student& st : s) cout << st.name << " ";
cout << endl;
return 0;
}> what you see
1 2 5 9 Suvd Tuul Bat
//LINE BY LINE
Watch it run
v = {5, 2, 9, 1}. No order at all.
Ties, and sorting only part of it
When two scores tie, which comes first? sort makes no promise. If the order matters, add a second test inside the comparator.
bool byScoreThenName(const Student& a, const Student& b) {
if (a.score != b.score) return a.score > b.score;
return a.name < b.name; // tie-break
}If you only need the top 3, you do not have to sort everything: partial_sort or nth_element are faster.