Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a vector of struct based on a specific field

Tags:

c++

sorting

Currently I am trying to sort a vector of structs based on a specific field. I have set up a custom comparison function for the use of the sort function. However, i am getting some errors with it.

Code:

    struct Play{
      int min, down, yard, locat;
      string Description, offname, defname;
      double relevance;
     };

    bool customCompare(const Play &x, const Play &y)
    {
        return (x.relevance < y.relevance);
    }

    void printResults()
    {
        sort(vecData.begin(),vecData.end(), customCompare);
    }`

Errors:

    error C3867: 'List::customCompare': function call missing argument list; use '&List::customCompare' to create a pointer to member
    error C2780: 'void std::sort(_RanIt,_RanIt)' : expects 2 arguments - 3 provided
like image 914
Rob Avatar asked Jan 12 '23 20:01

Rob


1 Answers

a) Use sort function with lambda notation as below( if you are using c++11)

 sort(vecData.begin(),vecData.end(), [](const Play &x, const Play &y){ return (x.relevance < y.relevance);});

Working code:

http://ideone.com/bDOrBV

b) Make comparator function as static

http://ideone.com/0HsaaH

like image 169
shivakumar Avatar answered Jan 17 '23 08:01

shivakumar