Answer the question
In order to leave comments, you need to log in
How to create a comporator for a vector of structures?
The task is to create a list of students that will contain the last name and the total scores for 3 exams (e1, e2, e3). There is a code
#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;
struct s
{
string name;
int balli;
};
int cmp(const void* a, const void* b)
{
return a.name < b.name;
}
int main()
{
vector<s> v;
int n = 0;
cin >> n;
v.reserve(n);
int e1, e2, e3;
string name;
for (int i = 0; i < n; i++)
{
cin >> name;
cin >> e1;
cin >> e2;
cin >> e3;
int bal = e1 + e2 + e3;
v.push_back({ name, bal });
}
qsort(v.data(), v.size(), sizeof(s), cmp);
for (vector<s>::iterator it = v.begin(); it != v.end(); it++)
{
cout << (*it).name << " " << (*it).balli << "\n";
}
return 0;
}
Answer the question
In order to leave comments, you need to log in
Help write a comporator for this case or explain what can be written differently.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question