0

I'm trying to sort a vector in descending order by average points of students ,but i don't know what is the correct way to do it? .It's my code now.

          void sortDes()
       {
       int len = students.size();
       for(int i = 0; i < len; i++)
       {
            for(int j = 0;j < len - 1; j++)
            {
              if(students[j].average()> students[j+1].average())
               {

                swap(students[j+1], students[j]);
               }
             }
        } 

       }
Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
Joe
  • 11
  • 2
  • 5

1 Answers1

1

Use std::sort with std::greater like this:

#include <functional>
#include <vector>
#include <algorithm>
int main()
{
    std::vector<int> Vec {2,5,4,8,1,2,2};
    std::sort(Vec.begin(), Vec.end(), std::greater<int>());// After sort will be 8,5,4,2,2,2,1
    return 0;
}

In your case it would be:

std::sort(students.begin(), students.end(), std::greater<int>());

For your CStudent override operator > as like this:

class CStudent
{
public:
    bool operator > (CStudent& cmp1)
    {
        //Do your own calculations here
        if ( cmp1.val < val )
        {
            return true;
        }

        return false;
    }
private:
    int val;
};

Then call sort with lambda:

//...
    std::sort(Vec.begin(), Vec.end(), [](CStudent& cmp1, CStudent& cmp2  )->bool{return cmp1 > cmp2;});
//...
Alexey Usachov
  • 1,364
  • 2
  • 8
  • 15
  • thank you, but i have pass,greater is undefined , i should create struck greater or something? – Joe Apr 27 '18 at 19:59
  • @Joe add #include – Alexey Usachov Apr 27 '18 at 20:00
  • Error 2 error C2664: 'bool std::greater::operator ()(const _Ty &,const _Ty &) const' : cannot convert argument 1 from 'CStudent' to 'const int &' c:\program files (x86)\microsoft visual studio 12.0\vc\include\algorithm 3071 1 Project1 – Joe Apr 27 '18 at 20:02
  • @Joe: You're not sorting integers, you're sorting your own `struct`. See [Sorting a vector of custom objects](https://stackoverflow.com/questions/1380463/sorting-a-vector-of-custom-objects). – Fred Larson Apr 27 '18 at 20:03
  • @Joe it is because you have container of CStudent, you need to override operator> in this class – Alexey Usachov Apr 27 '18 at 20:04