6

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
1
  • 2
    Make customCompare static. Commented Nov 23, 2013 at 19:48

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

Comments

5

Although this is an old question, I would like to note for the benefit of the future readers the possibility of directly sorting according to a specific field with the help of projections in the upcoming Ranges library in C++20:

ranges::sort(vecData, ranges::less, &Play::relevance);

This avoids the need of specifying two iterators or writing a custom comparison function or lambda.

Comments

2
static bool customCompare(const Play &x, const Play &y)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.