2

I wrote myself a compare function for sort(). It worked well when I put it this way.

bool comp(string a, string b)
{
    ...;
}

int main()
{
    sort(...,...,comp);
}

However, when I put all this inside a class, say:

class Test {

public:
    bool comp(string a,string b)
    {
        ...;
    }
    vector <string> CustomSort(vector <string> str) {
        sort(...,...,comp);
    }
};

There is a compile error "No matching function for call to 'sort ......'.

Why would this happen?

1
  • 5
    You should be using bool comp(const string &a, const string &b), I think. It doesn't affect the name lookup, but it surely affects the runtime efficiency (constructing and then destroying a new string for each argument on each comparison is relatively expensive). Commented Jan 14, 2012 at 19:17

1 Answer 1

6

Any nonstatic member function of class X has an extra argument - a reference/pointer to (const) X which becomes this. Therefore a member function's signature isn't such that can be digested by sort. You need to use boost::bind or std::mem_fun or std::mem_fun_ref. When using C++11, you can use std::bind.

std::sort(..., ..., std::bind(&Test::comp, this, _1, _2));

Come to think of it, the best solution in this case would be to make your comp function static, because it doesn't need this at all. In this case your original code will work without change.

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

1 Comment

Thanks a lot Armen :) Your reply is very informative. Making comp function static is the easiest way. And I'll need to learn more so that I could understand the concepts you mentioned.

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.