1

I have a Policy class with the following function:

double Policy::meanResponse();

Suppose I have a vector of Policy objects (myPolicies) that I wish to sort, and I wish to sort based on the value of Policy::meanResponse(). I have tried the following:

bool compare_by_function(const Policy& p1, const Policy& p2)
{
    return ( p1.meanResponse() < p2.meanResponse() );
}

sort(myPolicies.begin(), myPolicies.end(), compare_by_function);

But I get the error:

"error: passing 'const Policy' as 'this' argument of 'double Policy::meanResponse()' discards qualifers"

Can someone please explain how to correctly sort in this case?

4

1 回答 1

4

Did you try changing meanResponse to const?

double Policy::meanResponse()const;

Since you are passing the Policy objects to the compare function with const reference you can't call non-const methods on them.

http://www.parashift.com/c++-faq-lite/const-member-fns.html

于 2012-08-23T02:05:19.690 回答