Y
Y
yuki2020-09-13 08:56:47
C++ / C#
yuki, 2020-09-13 08:56:47

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;
}


It is necessary to sort first in descending order of points, and then, if some students have the same points, then in alphabetical order their last names. Help write a comporator for this case or explain what can be written differently.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
res2001, 2020-09-13
@res2001

Help write a comporator for this case or explain what can be written differently.

What are the problems?
Here's how the comparison process itself was described and how you implement the comparator.
Those. Check scores first. If the scores are not equal, immediately return the corresponding value.
If the scores are equal, you start checking name.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question