Search code examples
c++sortingstructure

Sorting a vector of structures based on one of the elements


I was writing a program to input the marks of n students in four subjects and then find the rank of one of them based on the total scores (from codeforces.com: https://codeforces.com/problemset/problem/1017/A). I thought storing the marks in a structure would help keeping track of the various subjects.

Now, what I did is simply implement a bubble sort on the vector while checking the total value. I want to know, is there a way that I can sort the vector based on just one of the members of the struct using std::sort()? Also, how do we make it descending?

Here is what the code looks like right now:

//The Structure
struct scores
{
    int eng, ger, mat, his, tot, rank;
    bool tommyVal;
};

//The Sort (present inside the main function)
    bool sorted = false;
    while (!sorted)
    {
        sorted = true;
        for (int i = 0; i < n-1; i++)
        {
            if (stud[i].tot < stud[i + 1].tot)
            {
                std::swap(stud[i], stud[i + 1]);
                sorted = false;
            }
        }
    }

Just in case you're interested, I need to find the rank of a student named Thomas. So, for that, I set the value of tommyVal true for his element, while I set it as false for the others. This way, I can easily locate Thomas' marks even though his location in the vector has changed after sorting it based on their total marks.

Also nice to know that std::swap() works for swapping entire structs as well. I wonder what other data structures it can swap.


Solution

  • std::sort() allows you to give it a predicate so you can perform comparisons however you want, eg:

    std::sort(
      stud.begin(),
      stud.begin()+n, // <-- use stud.end() instead if n == stud.size() ...
      [](const scores &a, const scores &b){ return a.tot < b.tot; }
    );
    

    Simply use return b.tot < a.tot to reverse the sorting order.